]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/App.java
37f5feecaca15e89185004625d05eb26c3a81852
[signal-cli] / src / main / java / org / asamk / signal / App.java
1 package org.asamk.signal;
2
3 import net.sourceforge.argparse4j.ArgumentParsers;
4 import net.sourceforge.argparse4j.impl.Arguments;
5 import net.sourceforge.argparse4j.inf.ArgumentParser;
6 import net.sourceforge.argparse4j.inf.Namespace;
7
8 import org.asamk.Signal;
9 import org.asamk.SignalControl;
10 import org.asamk.signal.commands.Command;
11 import org.asamk.signal.commands.Commands;
12 import org.asamk.signal.commands.LocalCommand;
13 import org.asamk.signal.commands.MultiLocalCommand;
14 import org.asamk.signal.commands.ProvisioningCommand;
15 import org.asamk.signal.commands.RegistrationCommand;
16 import org.asamk.signal.commands.exceptions.CommandException;
17 import org.asamk.signal.commands.exceptions.IOErrorException;
18 import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
19 import org.asamk.signal.commands.exceptions.UserErrorException;
20 import org.asamk.signal.dbus.DbusManagerImpl;
21 import org.asamk.signal.dbus.DbusMultiAccountManagerImpl;
22 import org.asamk.signal.dbus.DbusProvisioningManagerImpl;
23 import org.asamk.signal.dbus.DbusRegistrationManagerImpl;
24 import org.asamk.signal.manager.Manager;
25 import org.asamk.signal.manager.RegistrationManager;
26 import org.asamk.signal.manager.SignalAccountFiles;
27 import org.asamk.signal.manager.api.AccountCheckException;
28 import org.asamk.signal.manager.api.NotRegisteredException;
29 import org.asamk.signal.manager.config.ServiceConfig;
30 import org.asamk.signal.manager.config.ServiceEnvironment;
31 import org.asamk.signal.manager.storage.identities.TrustNewIdentity;
32 import org.asamk.signal.output.JsonWriterImpl;
33 import org.asamk.signal.output.OutputWriter;
34 import org.asamk.signal.output.PlainTextWriterImpl;
35 import org.asamk.signal.util.IOUtils;
36 import org.freedesktop.dbus.connections.impl.DBusConnection;
37 import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder;
38 import org.freedesktop.dbus.errors.ServiceUnknown;
39 import org.freedesktop.dbus.errors.UnknownMethod;
40 import org.freedesktop.dbus.exceptions.DBusException;
41 import org.freedesktop.dbus.exceptions.DBusExecutionException;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import java.io.BufferedWriter;
46 import java.io.File;
47 import java.io.IOException;
48 import java.io.OutputStreamWriter;
49
50 import static net.sourceforge.argparse4j.DefaultSettings.VERSION_0_9_0_DEFAULT_SETTINGS;
51
52 public class App {
53
54 private final static Logger logger = LoggerFactory.getLogger(App.class);
55
56 private final Namespace ns;
57
58 static ArgumentParser buildArgumentParser() {
59 var parser = ArgumentParsers.newFor("signal-cli", VERSION_0_9_0_DEFAULT_SETTINGS)
60 .includeArgumentNamesAsKeysInResult(true)
61 .build()
62 .defaultHelp(true)
63 .description("Commandline interface for Signal.")
64 .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
65
66 parser.addArgument("-v", "--version").help("Show package version.").action(Arguments.version());
67 parser.addArgument("--verbose")
68 .help("Raise log level and include lib signal logs. Specify multiple times for even more logs.")
69 .action(Arguments.count());
70 parser.addArgument("--log-file")
71 .type(File.class)
72 .help("Write log output to the given file. If --verbose is also given, the detailed logs will only be written to the log file.");
73 parser.addArgument("-c", "--config")
74 .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");
75
76 parser.addArgument("-a", "--account", "-u", "--username")
77 .help("Specify your phone number, that will be your identifier.");
78
79 var mut = parser.addMutuallyExclusiveGroup();
80 mut.addArgument("--dbus").dest("global-dbus").help("Make request via user dbus.").action(Arguments.storeTrue());
81 mut.addArgument("--dbus-system")
82 .dest("global-dbus-system")
83 .help("Make request via system dbus.")
84 .action(Arguments.storeTrue());
85
86 parser.addArgument("-o", "--output")
87 .help("Choose to output in plain text or JSON")
88 .type(Arguments.enumStringType(OutputType.class));
89
90 parser.addArgument("--service-environment")
91 .help("Choose the server environment to use.")
92 .type(Arguments.enumStringType(ServiceEnvironmentCli.class))
93 .setDefault(ServiceEnvironmentCli.LIVE);
94
95 parser.addArgument("--trust-new-identities")
96 .help("Choose when to trust new identities.")
97 .type(Arguments.enumStringType(TrustNewIdentityCli.class))
98 .setDefault(TrustNewIdentityCli.ON_FIRST_USE);
99
100 var subparsers = parser.addSubparsers().title("subcommands").dest("command");
101
102 Commands.getCommandSubparserAttachers().forEach((key, value) -> {
103 var subparser = subparsers.addParser(key);
104 value.attachToSubparser(subparser);
105 });
106
107 return parser;
108 }
109
110 public App(final Namespace ns) {
111 this.ns = ns;
112 }
113
114 public void init() throws CommandException {
115 var commandKey = ns.getString("command");
116 var command = Commands.getCommand(commandKey);
117 if (command == null) {
118 throw new UserErrorException("Command not implemented!");
119 }
120
121 var outputTypeInput = ns.<OutputType>get("output");
122 var outputType = outputTypeInput == null
123 ? command.getSupportedOutputTypes().stream().findFirst().orElse(null)
124 : outputTypeInput;
125 var writer = new BufferedWriter(new OutputStreamWriter(System.out, IOUtils.getConsoleCharset()));
126 var outputWriter = outputType == null
127 ? null
128 : outputType == OutputType.JSON ? new JsonWriterImpl(writer) : new PlainTextWriterImpl(writer);
129
130 if (outputWriter != null && !command.getSupportedOutputTypes().contains(outputType)) {
131 throw new UserErrorException("Command doesn't support output type " + outputType);
132 }
133
134 var account = ns.getString("account");
135
136 final var useDbus = Boolean.TRUE.equals(ns.getBoolean("global-dbus"));
137 final var useDbusSystem = Boolean.TRUE.equals(ns.getBoolean("global-dbus-system"));
138 if (useDbus || useDbusSystem) {
139 // If account is null, it will connect to the default object path
140 initDbusClient(command, account, useDbusSystem, outputWriter);
141 return;
142 }
143
144 if (!ServiceConfig.isSignalClientAvailable()) {
145 throw new UserErrorException("Missing required native library dependency: libsignal-client");
146 }
147
148 final File configPath;
149 var config = ns.getString("config");
150 if (config != null) {
151 configPath = new File(config);
152 } else {
153 configPath = getDefaultConfigPath();
154 }
155
156 final var serviceEnvironmentCli = ns.<ServiceEnvironmentCli>get("service-environment");
157 final var serviceEnvironment = serviceEnvironmentCli == ServiceEnvironmentCli.LIVE
158 ? ServiceEnvironment.LIVE
159 : ServiceEnvironment.STAGING;
160
161 final var trustNewIdentityCli = ns.<TrustNewIdentityCli>get("trust-new-identities");
162 final var trustNewIdentity = trustNewIdentityCli == TrustNewIdentityCli.ON_FIRST_USE
163 ? TrustNewIdentity.ON_FIRST_USE
164 : trustNewIdentityCli == TrustNewIdentityCli.ALWAYS ? TrustNewIdentity.ALWAYS : TrustNewIdentity.NEVER;
165
166 final SignalAccountFiles signalAccountFiles;
167 try {
168 signalAccountFiles = new SignalAccountFiles(configPath,
169 serviceEnvironment,
170 BaseConfig.USER_AGENT,
171 trustNewIdentity);
172 } catch (IOException e) {
173 throw new IOErrorException("Failed to read local accounts list", e);
174 }
175
176 if (command instanceof ProvisioningCommand provisioningCommand) {
177 if (account != null) {
178 throw new UserErrorException("You cannot specify a account (phone number) when linking");
179 }
180
181 handleProvisioningCommand(provisioningCommand, signalAccountFiles, outputWriter);
182 return;
183 }
184
185 if (account == null) {
186 if (command instanceof MultiLocalCommand multiLocalCommand) {
187 handleMultiLocalCommand(multiLocalCommand, signalAccountFiles, outputWriter);
188 return;
189 }
190
191 var accounts = signalAccountFiles.getAllLocalAccountNumbers();
192 if (accounts.size() == 0) {
193 throw new UserErrorException("No local users found, you first need to register or link an account");
194 } else if (accounts.size() > 1) {
195 throw new UserErrorException(
196 "Multiple users found, you need to specify an account (phone number) with -a");
197 }
198
199 account = accounts.stream().findFirst().get();
200 } else if (!Manager.isValidNumber(account, null)) {
201 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
202 }
203
204 if (command instanceof RegistrationCommand registrationCommand) {
205 handleRegistrationCommand(registrationCommand, account, signalAccountFiles);
206 return;
207 }
208
209 if (!(command instanceof LocalCommand)) {
210 throw new UserErrorException("Command only works in multi-account mode");
211 }
212
213 handleLocalCommand((LocalCommand) command, account, signalAccountFiles, outputWriter);
214 }
215
216 private void handleProvisioningCommand(
217 final ProvisioningCommand command,
218 final SignalAccountFiles signalAccountFiles,
219 final OutputWriter outputWriter
220 ) throws CommandException {
221 var pm = signalAccountFiles.initProvisioningManager();
222 command.handleCommand(ns, pm, outputWriter);
223 }
224
225 private void handleProvisioningCommand(
226 final ProvisioningCommand c, final DBusConnection dBusConn, final OutputWriter outputWriter
227 ) throws CommandException, DBusException {
228 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
229 DbusConfig.getObjectPath(),
230 SignalControl.class);
231 final var provisioningManager = new DbusProvisioningManagerImpl(signalControl, dBusConn);
232 try {
233 c.handleCommand(ns, provisioningManager, outputWriter);
234 } catch (UnsupportedOperationException e) {
235 throw new UserErrorException("Command is not yet implemented via dbus", e);
236 } catch (DBusExecutionException e) {
237 throw new UnexpectedErrorException(e.getMessage(), e);
238 }
239 }
240
241 private void handleRegistrationCommand(
242 final RegistrationCommand command, final String account, final SignalAccountFiles signalAccountFiles
243 ) throws CommandException {
244 try (final var manager = loadRegistrationManager(account, signalAccountFiles)) {
245 command.handleCommand(ns, manager);
246 } catch (IOException e) {
247 logger.warn("Cleanup failed", e);
248 }
249 }
250
251 private void handleRegistrationCommand(
252 final RegistrationCommand c, String account, final DBusConnection dBusConn, final OutputWriter outputWriter
253 ) throws CommandException, DBusException {
254 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
255 DbusConfig.getObjectPath(),
256 SignalControl.class);
257 try (final var registrationManager = new DbusRegistrationManagerImpl(account, signalControl, dBusConn)) {
258 c.handleCommand(ns, registrationManager);
259 } catch (UnsupportedOperationException e) {
260 throw new UserErrorException("Command is not yet implemented via dbus", e);
261 } catch (DBusExecutionException e) {
262 throw new UnexpectedErrorException(e.getMessage(), e);
263 }
264 }
265
266 private void handleLocalCommand(
267 final LocalCommand command,
268 final String account,
269 final SignalAccountFiles signalAccountFiles,
270 final OutputWriter outputWriter
271 ) throws CommandException {
272 try (var m = loadManager(account, signalAccountFiles)) {
273 command.handleCommand(ns, m, outputWriter);
274 } catch (IOException e) {
275 logger.warn("Cleanup failed", e);
276 }
277 }
278
279 private void handleLocalCommand(
280 final LocalCommand c,
281 String accountObjectPath,
282 final DBusConnection dBusConn,
283 final OutputWriter outputWriter
284 ) throws CommandException, DBusException {
285 var signal = dBusConn.getRemoteObject(DbusConfig.getBusname(), accountObjectPath, Signal.class);
286 try (final var m = new DbusManagerImpl(signal, dBusConn)) {
287 c.handleCommand(ns, m, outputWriter);
288 } catch (UnsupportedOperationException e) {
289 throw new UserErrorException("Command is not yet implemented via dbus", e);
290 } catch (DBusExecutionException e) {
291 throw new UnexpectedErrorException(e.getMessage(), e);
292 }
293 }
294
295 private void handleMultiLocalCommand(
296 final MultiLocalCommand command,
297 final SignalAccountFiles signalAccountFiles,
298 final OutputWriter outputWriter
299 ) throws CommandException {
300 try (var multiAccountManager = signalAccountFiles.initMultiAccountManager()) {
301 command.handleCommand(ns, multiAccountManager, outputWriter);
302 }
303 }
304
305 private void handleMultiLocalCommand(
306 final MultiLocalCommand c, final DBusConnection dBusConn, final OutputWriter outputWriter
307 ) throws CommandException, DBusException {
308 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
309 DbusConfig.getObjectPath(),
310 SignalControl.class);
311 try (final var multiAccountManager = new DbusMultiAccountManagerImpl(signalControl, dBusConn)) {
312 c.handleCommand(ns, multiAccountManager, outputWriter);
313 } catch (UnsupportedOperationException e) {
314 throw new UserErrorException("Command is not yet implemented via dbus", e);
315 }
316 }
317
318 private RegistrationManager loadRegistrationManager(
319 final String account, final SignalAccountFiles signalAccountFiles
320 ) throws UnexpectedErrorException {
321 try {
322 return signalAccountFiles.initRegistrationManager(account);
323 } catch (Throwable e) {
324 throw new UnexpectedErrorException("Error loading or creating state file: "
325 + e.getMessage()
326 + " ("
327 + e.getClass().getSimpleName()
328 + ")", e);
329 }
330 }
331
332 private Manager loadManager(
333 final String account, final SignalAccountFiles signalAccountFiles
334 ) throws CommandException {
335 logger.trace("Loading account file for {}", account);
336 try {
337 return signalAccountFiles.initManager(account);
338 } catch (NotRegisteredException e) {
339 throw new UserErrorException("User " + account + " is not registered.");
340 } catch (AccountCheckException ace) {
341 if (ace.getCause() instanceof IOException e) {
342 throw new IOErrorException("Error while checking account " + account + ": " + e.getMessage(), e);
343 } else {
344 throw new UnexpectedErrorException("Error while checking account " + account + ": " + ace.getMessage(),
345 ace);
346 }
347 } catch (Throwable e) {
348 throw new UnexpectedErrorException("Error loading state file for user "
349 + account
350 + ": "
351 + e.getMessage()
352 + " ("
353 + e.getClass().getSimpleName()
354 + ")", e);
355 }
356 }
357
358 private void initDbusClient(
359 final Command command, final String account, final boolean systemBus, final OutputWriter outputWriter
360 ) throws CommandException {
361 try {
362 DBusConnection.DBusBusType busType;
363 if (systemBus) {
364 busType = DBusConnection.DBusBusType.SYSTEM;
365 } else {
366 busType = DBusConnection.DBusBusType.SESSION;
367 }
368 try (var dBusConn = DBusConnectionBuilder.forType(busType).build()) {
369 if (command instanceof ProvisioningCommand c) {
370 if (account != null) {
371 throw new UserErrorException("You cannot specify a account (phone number) when linking");
372 }
373
374 handleProvisioningCommand(c, dBusConn, outputWriter);
375 return;
376 }
377
378 if (account == null && command instanceof MultiLocalCommand c) {
379 handleMultiLocalCommand(c, dBusConn, outputWriter);
380 return;
381 }
382 if (account != null && command instanceof RegistrationCommand c) {
383 handleRegistrationCommand(c, account, dBusConn, outputWriter);
384 return;
385 }
386 if (!(command instanceof LocalCommand localCommand)) {
387 throw new UserErrorException("Command only works in multi-account mode");
388 }
389
390 var accountObjectPath = account == null ? tryGetSingleAccountObjectPath(dBusConn) : null;
391 if (accountObjectPath == null) {
392 accountObjectPath = DbusConfig.getObjectPath(account);
393 }
394 handleLocalCommand(localCommand, accountObjectPath, dBusConn, outputWriter);
395 }
396 } catch (ServiceUnknown e) {
397 throw new UserErrorException("signal-cli DBus daemon not running on "
398 + (systemBus ? "system" : "session")
399 + " bus: "
400 + e.getMessage(), e);
401 } catch (DBusExecutionException | DBusException | IOException e) {
402 throw new UnexpectedErrorException("Dbus client failed: " + e.getMessage(), e);
403 }
404 }
405
406 private String tryGetSingleAccountObjectPath(final DBusConnection dBusConn) throws DBusException, CommandException {
407 var control = dBusConn.getRemoteObject(DbusConfig.getBusname(),
408 DbusConfig.getObjectPath(),
409 SignalControl.class);
410 try {
411 final var accounts = control.listAccounts();
412 if (accounts.size() == 0) {
413 throw new UserErrorException("No local users found, you first need to register or link an account");
414 } else if (accounts.size() > 1) {
415 throw new UserErrorException(
416 "Multiple users found, you need to specify an account (phone number) with -a");
417 }
418
419 return accounts.get(0).getPath();
420 } catch (UnknownMethod e) {
421 // dbus daemon not running in multi-account mode
422 return null;
423 }
424 }
425
426 /**
427 * @return the default data directory to be used by signal-cli.
428 */
429 private static File getDefaultConfigPath() {
430 return new File(IOUtils.getDataHomeDir(), "signal-cli");
431 }
432 }