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;
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;
import org.asamk.signal.manager.RegistrationManager;
-import org.asamk.signal.manager.ServiceConfig;
+import org.asamk.signal.manager.config.ServiceConfig;
+import org.asamk.signal.manager.config.ServiceEnvironment;
import org.asamk.signal.util.IOUtils;
import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
-import org.whispersystems.signalservice.internal.configuration.SignalServiceConfiguration;
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 {
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.")
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());
.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, SANDBOX or LIVE.")
+ .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);
}
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 SignalServiceConfiguration serviceConfiguration = ServiceConfig.createDefaultServiceConfiguration(
- BaseConfig.USER_AGENT);
+ 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, serviceConfiguration);
+ 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, serviceConfiguration, 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, serviceConfiguration);
+ 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, serviceConfiguration);
+ handleLocalCommand((LocalCommand) command, username, dataPath, serviceEnvironment);
}
- private int handleProvisioningCommand(
- final ProvisioningCommand command,
- final File dataPath,
- final SignalServiceConfiguration serviceConfiguration
- ) {
- ProvisioningManager pm = new ProvisioningManager(dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
- return command.handleCommand(ns, pm);
+ private void handleProvisioningCommand(
+ final ProvisioningCommand command, final File dataPath, final ServiceEnvironment serviceEnvironment
+ ) 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 SignalServiceConfiguration serviceConfiguration
- ) {
+ final ServiceEnvironment serviceEnvironment
+ ) throws CommandException {
final RegistrationManager manager;
try {
- manager = RegistrationManager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
+ 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 SignalServiceConfiguration serviceConfiguration
- ) {
- try (Manager m = loadManager(username, dataPath, serviceConfiguration)) {
- if (m == null) {
- return 2;
- }
-
- return command.handleCommand(ns, m);
+ final ServiceEnvironment serviceEnvironment
+ ) 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 SignalServiceConfiguration serviceConfiguration,
+ final ServiceEnvironment serviceEnvironment,
final List<String> usernames
- ) {
- final List<Manager> managers = usernames.stream()
- .map(u -> loadManager(u, dataPath, serviceConfiguration))
- .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 SignalServiceConfiguration serviceConfiguration
- ) {
+ final String username, final File dataPath, final ServiceEnvironment serviceEnvironment
+ ) throws CommandException {
Manager manager;
try {
- manager = Manager.init(username, dataPath, serviceConfiguration, BaseConfig.USER_AGENT);
+ 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) {
} 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");
}
}
* @return the data directory to be used by signal-cli.
*/
private static File getDefaultDataPath() {
- File dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
+ var dataPath = new File(IOUtils.getDataHomeDir(), "signal-cli");
if (dataPath.exists()) {
return dataPath;
}
- File configPath = new File(System.getProperty("user.home"), ".config");
+ var configPath = new File(System.getProperty("user.home"), ".config");
- File legacySettingsPath = new File(configPath, "signal");
+ var legacySettingsPath = new File(configPath, "signal");
if (legacySettingsPath.exists()) {
+ logger.warn("Using legacy data path \"{}\", please move it to \"{}\".", legacySettingsPath, dataPath);
return legacySettingsPath;
}
legacySettingsPath = new File(configPath, "textsecure");
if (legacySettingsPath.exists()) {
+ logger.warn("Using legacy data path \"{}\", please move it to \"{}\".", legacySettingsPath, dataPath);
return legacySettingsPath;
}