+ final var signalAccountFiles = loadSignalAccountFiles();
+
+ 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, signalAccountFiles, commandHandler);
+ return;
+ }
+
+ if (account == null) {
+ if (command instanceof MultiLocalCommand multiLocalCommand) {
+ handleMultiLocalCommand(multiLocalCommand, signalAccountFiles, commandHandler);
+ return;
+ }
+
+ 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, signalAccountFiles, commandHandler);
+ return;
+ }
+
+ 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 {