]> nmode's Git Repositories - signal-cli/blobdiff - src/main/java/org/asamk/signal/App.java
Remove fallbacks to deprecated data paths
[signal-cli] / src / main / java / org / asamk / signal / App.java
index e35285c3da624a4a9e4f8169b0ca370540848141..9e410d2f10c96df4bbd79f024f2a5f319d56622a 100644 (file)
@@ -3,10 +3,7 @@ package org.asamk.signal;
 import net.sourceforge.argparse4j.ArgumentParsers;
 import net.sourceforge.argparse4j.impl.Arguments;
 import net.sourceforge.argparse4j.inf.ArgumentParser;
-import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
 import net.sourceforge.argparse4j.inf.Namespace;
-import net.sourceforge.argparse4j.inf.Subparser;
-import net.sourceforge.argparse4j.inf.Subparsers;
 
 import org.asamk.Signal;
 import org.asamk.signal.commands.Command;
@@ -17,6 +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.exceptions.CommandException;
+import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
+import org.asamk.signal.commands.exceptions.UserErrorException;
 import org.asamk.signal.manager.Manager;
 import org.asamk.signal.manager.NotRegisteredException;
 import org.asamk.signal.manager.ProvisioningManager;
@@ -32,10 +32,10 @@ import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
 
 import java.io.File;
 import java.io.IOException;
+import java.util.ArrayList;
 import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.stream.Collectors;
+
+import static net.sourceforge.argparse4j.DefaultSettings.VERSION_0_9_0_DEFAULT_SETTINGS;
 
 public class App {
 
@@ -44,7 +44,8 @@ public class App {
     private final Namespace ns;
 
     static ArgumentParser buildArgumentParser() {
-        ArgumentParser 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.")
@@ -57,9 +58,9 @@ 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.");
 
-        MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
+        var mut = parser.addMutuallyExclusiveGroup();
         mut.addArgument("--dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
         mut.addArgument("--dbus-system").help("Make request via system dbus.").action(Arguments.storeTrue());
 
@@ -68,11 +69,16 @@ public class App {
                 .type(Arguments.enumStringType(OutputType.class))
                 .setDefault(OutputType.PLAIN_TEXT);
 
-        Subparsers subparsers = parser.addSubparsers().title("subcommands").dest("command");
+        parser.addArgument("--service-environment")
+                .help("Choose the server environment to use.")
+                .type(Arguments.enumStringType(ServiceEnvironmentCli.class))
+                .setDefault(ServiceEnvironmentCli.LIVE);
+
+        var subparsers = parser.addSubparsers().title("subcommands").dest("command");
 
-        final Map<String, Command> commands = Commands.getCommands();
-        for (Map.Entry<String, Command> entry : commands.entrySet()) {
-            Subparser subparser = subparsers.addParser(entry.getKey());
+        final var commands = Commands.getCommands();
+        for (var entry : commands.entrySet()) {
+            var subparser = subparsers.addParser(entry.getKey());
             entry.getValue().attachToSubparser(subparser);
         }
 
@@ -83,181 +89,191 @@ public class App {
         this.ns = ns;
     }
 
-    public int init() {
-        String commandKey = ns.getString("command");
-        Command command = Commands.getCommand(commandKey);
+    public void init() throws CommandException {
+        var commandKey = ns.getString("command");
+        var command = Commands.getCommand(commandKey);
         if (command == null) {
-            logger.error("Command not implemented!");
-            return 1;
+            throw new UserErrorException("Command not implemented!");
         }
 
-        OutputType outputType = ns.get("output");
+        var outputType = ns.<OutputType>get("output");
         if (!command.getSupportedOutputTypes().contains(outputType)) {
-            logger.error("Command doesn't support output type {}", outputType.toString());
-            return 1;
+            throw new UserErrorException("Command doesn't support output type " + outputType.toString());
         }
 
-        String username = ns.getString("username");
+        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
-            return initDbusClient(command, username, useDbusSystem);
+            initDbusClient(command, username, useDbusSystem);
+            return;
         }
 
         final File dataPath;
-        String config = ns.getString("config");
+        var config = ns.getString("config");
         if (config != null) {
             dataPath = new File(config);
         } else {
             dataPath = getDefaultDataPath();
         }
 
-        final ServiceEnvironment serviceEnvironment = ServiceEnvironment.LIVE;
+        final var serviceEnvironmentCli = ns.<ServiceEnvironmentCli>get("service-environment");
+        final var serviceEnvironment = serviceEnvironmentCli == ServiceEnvironmentCli.LIVE
+                ? ServiceEnvironment.LIVE
+                : ServiceEnvironment.SANDBOX;
 
         if (!ServiceConfig.getCapabilities().isGv2()) {
             logger.warn("WARNING: Support for new group V2 is disabled,"
                     + " because the required native library dependency is missing: libzkgroup");
         }
 
+        if (!ServiceConfig.isSignalClientAvailable()) {
+            throw new UserErrorException("Missing required native library dependency: libsignal-client");
+        }
+
         if (command instanceof ProvisioningCommand) {
             if (username != null) {
-                System.err.println("You cannot specify a username (phone number) when linking");
-                return 1;
+                throw new UserErrorException("You cannot specify a username (phone number) when linking");
             }
 
-            return handleProvisioningCommand((ProvisioningCommand) command, dataPath, serviceEnvironment);
+            handleProvisioningCommand((ProvisioningCommand) command, dataPath, serviceEnvironment);
+            return;
         }
 
         if (username == null) {
-            List<String> usernames = Manager.getAllLocalUsernames(dataPath);
-            if (usernames.size() == 0) {
-                System.err.println("No local users found, you first need to register or link an account");
-                return 1;
-            }
+            var usernames = Manager.getAllLocalUsernames(dataPath);
 
             if (command instanceof MultiLocalCommand) {
-                return handleMultiLocalCommand((MultiLocalCommand) command, dataPath, serviceEnvironment, usernames);
+                handleMultiLocalCommand((MultiLocalCommand) command, dataPath, serviceEnvironment, usernames);
+                return;
             }
 
-            if (usernames.size() > 1) {
-                System.err.println("Multiple users found, you need to specify a username (phone number) with -u");
-                return 1;
+            if (usernames.size() == 0) {
+                throw new UserErrorException("No local users found, you first need to register or link an account");
+            } else if (usernames.size() > 1) {
+                throw new UserErrorException(
+                        "Multiple users found, you need to specify a username (phone number) with -u");
             }
 
             username = usernames.get(0);
         } else if (!PhoneNumberFormatter.isValidNumber(username, null)) {
-            System.err.println("Invalid username (phone number), make sure you include the country code.");
-            return 1;
+            throw new UserErrorException("Invalid username (phone number), make sure you include the country code.");
         }
 
         if (command instanceof RegistrationCommand) {
-            return handleRegistrationCommand((RegistrationCommand) command, username, dataPath, serviceEnvironment);
+            handleRegistrationCommand((RegistrationCommand) command, username, dataPath, serviceEnvironment);
+            return;
         }
 
         if (!(command instanceof LocalCommand)) {
-            System.err.println("Command only works via dbus");
-            return 1;
+            throw new UserErrorException("Command only works via dbus");
         }
 
-        return handleLocalCommand((LocalCommand) command, username, dataPath, serviceEnvironment);
+        handleLocalCommand((LocalCommand) command, username, dataPath, serviceEnvironment);
     }
 
-    private int handleProvisioningCommand(
+    private void handleProvisioningCommand(
             final ProvisioningCommand command, final File dataPath, final ServiceEnvironment serviceEnvironment
-    ) {
-        ProvisioningManager pm = ProvisioningManager.init(dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
-        return command.handleCommand(ns, pm);
+    ) throws CommandException {
+        var pm = ProvisioningManager.init(dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
+        command.handleCommand(ns, pm);
     }
 
-    private int handleRegistrationCommand(
+    private void handleRegistrationCommand(
             final RegistrationCommand command,
             final String username,
             final File dataPath,
             final ServiceEnvironment serviceEnvironment
-    ) {
+    ) throws CommandException {
         final RegistrationManager manager;
         try {
             manager = RegistrationManager.init(username, dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
         } catch (Throwable e) {
-            logger.error("Error loading or creating state file: {}", e.getMessage());
-            return 2;
+            throw new UnexpectedErrorException("Error loading or creating state file: "
+                    + e.getMessage()
+                    + " ("
+                    + e.getClass().getSimpleName()
+                    + ")");
         }
-        try (RegistrationManager m = manager) {
-            return command.handleCommand(ns, m);
+        try (var m = manager) {
+            command.handleCommand(ns, m);
         } catch (IOException e) {
-            logger.error("Cleanup failed", e);
-            return 2;
+            logger.warn("Cleanup failed", e);
         }
     }
 
-    private int handleLocalCommand(
+    private void handleLocalCommand(
             final LocalCommand command,
             final String username,
             final File dataPath,
             final ServiceEnvironment serviceEnvironment
-    ) {
-        try (Manager m = loadManager(username, dataPath, serviceEnvironment)) {
-            if (m == null) {
-                return 2;
-            }
-
-            return command.handleCommand(ns, m);
+    ) throws CommandException {
+        try (var m = loadManager(username, dataPath, serviceEnvironment)) {
+            command.handleCommand(ns, m);
         } catch (IOException e) {
-            logger.error("Cleanup failed", e);
-            return 2;
+            logger.warn("Cleanup failed", e);
         }
     }
 
-    private int handleMultiLocalCommand(
+    private void handleMultiLocalCommand(
             final MultiLocalCommand command,
             final File dataPath,
             final ServiceEnvironment serviceEnvironment,
             final List<String> usernames
-    ) {
-        final List<Manager> managers = usernames.stream()
-                .map(u -> loadManager(u, dataPath, serviceEnvironment))
-                .filter(Objects::nonNull)
-                .collect(Collectors.toList());
+    ) throws CommandException {
+        final var managers = new ArrayList<Manager>();
+        for (String u : usernames) {
+            try {
+                managers.add(loadManager(u, dataPath, serviceEnvironment));
+            } catch (CommandException e) {
+                logger.warn("Ignoring {}: {}", u, e.getMessage());
+            }
+        }
 
-        int result = command.handleCommand(ns, managers);
+        command.handleCommand(ns, managers);
 
-        for (Manager m : managers) {
+        for (var m : managers) {
             try {
                 m.close();
             } catch (IOException e) {
                 logger.warn("Cleanup failed", e);
             }
         }
-        return result;
     }
 
     private Manager loadManager(
             final String username, final File dataPath, final ServiceEnvironment serviceEnvironment
-    ) {
+    ) throws CommandException {
         Manager manager;
         try {
             manager = Manager.init(username, dataPath, serviceEnvironment, BaseConfig.USER_AGENT);
         } catch (NotRegisteredException e) {
-            logger.error("User " + username + " is not registered.");
-            return null;
+            throw new UserErrorException("User " + username + " is not registered.");
         } catch (Throwable e) {
-            logger.error("Error loading state file for user " + username + ": {}", e.getMessage());
-            return null;
+            logger.debug("Loading state file failed", e);
+            throw new UnexpectedErrorException("Error loading state file for user "
+                    + username
+                    + ": "
+                    + e.getMessage()
+                    + " ("
+                    + e.getClass().getSimpleName()
+                    + ")");
         }
 
         try {
             manager.checkAccountState();
         } catch (IOException e) {
-            logger.error("Error while checking account " + username + ": {}", e.getMessage());
-            return null;
+            throw new UnexpectedErrorException("Error while checking account " + username + ": " + e.getMessage());
         }
 
         return manager;
     }
 
-    private int initDbusClient(final Command command, final String username, final boolean systemBus) {
+    private void initDbusClient(
+            final Command command, final String username, final boolean systemBus
+    ) throws CommandException {
         try {
             DBusConnection.DBusBusType busType;
             if (systemBus) {
@@ -265,55 +281,33 @@ public class App {
             } else {
                 busType = DBusConnection.DBusBusType.SESSION;
             }
-            try (DBusConnection dBusConn = DBusConnection.getConnection(busType)) {
-                Signal ts = dBusConn.getRemoteObject(DbusConfig.getBusname(),
+            try (var dBusConn = DBusConnection.getConnection(busType)) {
+                var ts = dBusConn.getRemoteObject(DbusConfig.getBusname(),
                         DbusConfig.getObjectPath(username),
                         Signal.class);
 
-                return handleCommand(command, ts, dBusConn);
+                handleCommand(command, ts, dBusConn);
             }
         } catch (DBusException | IOException e) {
             logger.error("Dbus client failed", e);
-            return 2;
+            throw new UnexpectedErrorException("Dbus client failed");
         }
     }
 
-    private int handleCommand(Command command, Signal ts, DBusConnection dBusConn) {
+    private void handleCommand(Command command, Signal ts, DBusConnection dBusConn) throws CommandException {
         if (command instanceof ExtendedDbusCommand) {
-            return ((ExtendedDbusCommand) command).handleCommand(ns, ts, dBusConn);
+            ((ExtendedDbusCommand) command).handleCommand(ns, ts, dBusConn);
         } else if (command instanceof DbusCommand) {
-            return ((DbusCommand) command).handleCommand(ns, ts);
+            ((DbusCommand) command).handleCommand(ns, ts);
         } else {
-            System.err.println("Command is not yet implemented via dbus");
-            return 1;
+            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() {
-        File dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
-        if (dataPath.exists()) {
-            return dataPath;
-        }
-
-        File configPath = new File(System.getProperty("user.home"), ".config");
-
-        File 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");
     }
 }