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