]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/App.java
Add SignalAccountFiles as a central entry point
[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.errors.ServiceUnknown;
38 import org.freedesktop.dbus.errors.UnknownMethod;
39 import org.freedesktop.dbus.exceptions.DBusException;
40 import org.freedesktop.dbus.exceptions.DBusExecutionException;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import java.io.BufferedWriter;
45 import java.io.File;
46 import java.io.IOException;
47 import java.io.OutputStreamWriter;
48 import java.nio.charset.Charset;
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, Charset.defaultCharset()));
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 = new SignalAccountFiles(configPath,
167 serviceEnvironment,
168 BaseConfig.USER_AGENT,
169 trustNewIdentity);
170
171 if (command instanceof ProvisioningCommand provisioningCommand) {
172 if (account != null) {
173 throw new UserErrorException("You cannot specify a account (phone number) when linking");
174 }
175
176 handleProvisioningCommand(provisioningCommand, signalAccountFiles, outputWriter);
177 return;
178 }
179
180 if (account == null) {
181 if (command instanceof MultiLocalCommand multiLocalCommand) {
182 handleMultiLocalCommand(multiLocalCommand, signalAccountFiles, outputWriter);
183 return;
184 }
185
186 var accounts = signalAccountFiles.getAllLocalAccountNumbers();
187 if (accounts.size() == 0) {
188 throw new UserErrorException("No local users found, you first need to register or link an account");
189 } else if (accounts.size() > 1) {
190 throw new UserErrorException(
191 "Multiple users found, you need to specify an account (phone number) with -a");
192 }
193
194 account = accounts.stream().findFirst().get();
195 } else if (!Manager.isValidNumber(account, null)) {
196 throw new UserErrorException("Invalid account (phone number), make sure you include the country code.");
197 }
198
199 if (command instanceof RegistrationCommand registrationCommand) {
200 handleRegistrationCommand(registrationCommand, account, signalAccountFiles);
201 return;
202 }
203
204 if (!(command instanceof LocalCommand)) {
205 throw new UserErrorException("Command only works in multi-account mode");
206 }
207
208 handleLocalCommand((LocalCommand) command, account, signalAccountFiles, outputWriter);
209 }
210
211 private void handleProvisioningCommand(
212 final ProvisioningCommand command,
213 final SignalAccountFiles signalAccountFiles,
214 final OutputWriter outputWriter
215 ) throws CommandException {
216 var pm = signalAccountFiles.initProvisioningManager();
217 command.handleCommand(ns, pm, outputWriter);
218 }
219
220 private void handleProvisioningCommand(
221 final ProvisioningCommand c, final DBusConnection dBusConn, final OutputWriter outputWriter
222 ) throws CommandException, DBusException {
223 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
224 DbusConfig.getObjectPath(),
225 SignalControl.class);
226 final var provisioningManager = new DbusProvisioningManagerImpl(signalControl, dBusConn);
227 try {
228 c.handleCommand(ns, provisioningManager, outputWriter);
229 } catch (UnsupportedOperationException e) {
230 throw new UserErrorException("Command is not yet implemented via dbus", e);
231 } catch (DBusExecutionException e) {
232 throw new UnexpectedErrorException(e.getMessage(), e);
233 }
234 }
235
236 private void handleRegistrationCommand(
237 final RegistrationCommand command, final String account, final SignalAccountFiles signalAccountFiles
238 ) throws CommandException {
239 try (final var manager = loadRegistrationManager(account, signalAccountFiles)) {
240 command.handleCommand(ns, manager);
241 } catch (IOException e) {
242 logger.warn("Cleanup failed", e);
243 }
244 }
245
246 private void handleRegistrationCommand(
247 final RegistrationCommand c, String account, final DBusConnection dBusConn, final OutputWriter outputWriter
248 ) throws CommandException, DBusException {
249 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
250 DbusConfig.getObjectPath(),
251 SignalControl.class);
252 try (final var registrationManager = new DbusRegistrationManagerImpl(account, signalControl, dBusConn)) {
253 c.handleCommand(ns, registrationManager);
254 } catch (UnsupportedOperationException e) {
255 throw new UserErrorException("Command is not yet implemented via dbus", e);
256 } catch (DBusExecutionException e) {
257 throw new UnexpectedErrorException(e.getMessage(), e);
258 }
259 }
260
261 private void handleLocalCommand(
262 final LocalCommand command,
263 final String account,
264 final SignalAccountFiles signalAccountFiles,
265 final OutputWriter outputWriter
266 ) throws CommandException {
267 try (var m = loadManager(account, signalAccountFiles)) {
268 command.handleCommand(ns, m, outputWriter);
269 } catch (IOException e) {
270 logger.warn("Cleanup failed", e);
271 }
272 }
273
274 private void handleLocalCommand(
275 final LocalCommand c,
276 String accountObjectPath,
277 final DBusConnection dBusConn,
278 final OutputWriter outputWriter
279 ) throws CommandException, DBusException {
280 var signal = dBusConn.getRemoteObject(DbusConfig.getBusname(), accountObjectPath, Signal.class);
281 try (final var m = new DbusManagerImpl(signal, dBusConn)) {
282 c.handleCommand(ns, m, outputWriter);
283 } catch (UnsupportedOperationException e) {
284 throw new UserErrorException("Command is not yet implemented via dbus", e);
285 } catch (DBusExecutionException e) {
286 throw new UnexpectedErrorException(e.getMessage(), e);
287 }
288 }
289
290 private void handleMultiLocalCommand(
291 final MultiLocalCommand command,
292 final SignalAccountFiles signalAccountFiles,
293 final OutputWriter outputWriter
294 ) throws CommandException {
295 try (var multiAccountManager = signalAccountFiles.initMultiAccountManager()) {
296 command.handleCommand(ns, multiAccountManager, outputWriter);
297 }
298 }
299
300 private void handleMultiLocalCommand(
301 final MultiLocalCommand c, final DBusConnection dBusConn, final OutputWriter outputWriter
302 ) throws CommandException, DBusException {
303 final var signalControl = dBusConn.getRemoteObject(DbusConfig.getBusname(),
304 DbusConfig.getObjectPath(),
305 SignalControl.class);
306 try (final var multiAccountManager = new DbusMultiAccountManagerImpl(signalControl, dBusConn)) {
307 c.handleCommand(ns, multiAccountManager, outputWriter);
308 } catch (UnsupportedOperationException e) {
309 throw new UserErrorException("Command is not yet implemented via dbus", e);
310 }
311 }
312
313 private RegistrationManager loadRegistrationManager(
314 final String account, final SignalAccountFiles signalAccountFiles
315 ) throws UnexpectedErrorException {
316 try {
317 return signalAccountFiles.initRegistrationManager(account);
318 } catch (Throwable e) {
319 throw new UnexpectedErrorException("Error loading or creating state file: "
320 + e.getMessage()
321 + " ("
322 + e.getClass().getSimpleName()
323 + ")", e);
324 }
325 }
326
327 private Manager loadManager(
328 final String account, final SignalAccountFiles signalAccountFiles
329 ) throws CommandException {
330 logger.trace("Loading account file for {}", account);
331 try {
332 return signalAccountFiles.initManager(account);
333 } catch (NotRegisteredException e) {
334 throw new UserErrorException("User " + account + " is not registered.");
335 } catch (AccountCheckException ace) {
336 if (ace.getCause() instanceof IOException e) {
337 throw new IOErrorException("Error while checking account " + account + ": " + e.getMessage(), e);
338 } else {
339 throw new UnexpectedErrorException("Error while checking account " + account + ": " + ace.getMessage(),
340 ace);
341 }
342 } catch (Throwable e) {
343 throw new UnexpectedErrorException("Error loading state file for user "
344 + account
345 + ": "
346 + e.getMessage()
347 + " ("
348 + e.getClass().getSimpleName()
349 + ")", e);
350 }
351 }
352
353 private void initDbusClient(
354 final Command command, final String account, final boolean systemBus, final OutputWriter outputWriter
355 ) throws CommandException {
356 try {
357 DBusConnection.DBusBusType busType;
358 if (systemBus) {
359 busType = DBusConnection.DBusBusType.SYSTEM;
360 } else {
361 busType = DBusConnection.DBusBusType.SESSION;
362 }
363 try (var dBusConn = DBusConnection.getConnection(busType)) {
364 if (command instanceof ProvisioningCommand c) {
365 if (account != null) {
366 throw new UserErrorException("You cannot specify a account (phone number) when linking");
367 }
368
369 handleProvisioningCommand(c, dBusConn, outputWriter);
370 return;
371 }
372
373 if (account == null && command instanceof MultiLocalCommand c) {
374 handleMultiLocalCommand(c, dBusConn, outputWriter);
375 return;
376 }
377 if (account != null && command instanceof RegistrationCommand c) {
378 handleRegistrationCommand(c, account, dBusConn, outputWriter);
379 return;
380 }
381 if (!(command instanceof LocalCommand localCommand)) {
382 throw new UserErrorException("Command only works in multi-account mode");
383 }
384
385 var accountObjectPath = account == null ? tryGetSingleAccountObjectPath(dBusConn) : null;
386 if (accountObjectPath == null) {
387 accountObjectPath = DbusConfig.getObjectPath(account);
388 }
389 handleLocalCommand(localCommand, accountObjectPath, dBusConn, outputWriter);
390 }
391 } catch (ServiceUnknown e) {
392 throw new UserErrorException("signal-cli DBus daemon not running on "
393 + (systemBus ? "system" : "session")
394 + " bus: "
395 + e.getMessage(), e);
396 } catch (DBusExecutionException | DBusException | IOException e) {
397 throw new UnexpectedErrorException("Dbus client failed: " + e.getMessage(), e);
398 }
399 }
400
401 private String tryGetSingleAccountObjectPath(final DBusConnection dBusConn) throws DBusException, CommandException {
402 var control = dBusConn.getRemoteObject(DbusConfig.getBusname(),
403 DbusConfig.getObjectPath(),
404 SignalControl.class);
405 try {
406 final var accounts = control.listAccounts();
407 if (accounts.size() == 0) {
408 throw new UserErrorException("No local users found, you first need to register or link an account");
409 } else if (accounts.size() > 1) {
410 throw new UserErrorException(
411 "Multiple users found, you need to specify an account (phone number) with -a");
412 }
413
414 return accounts.get(0).getPath();
415 } catch (UnknownMethod e) {
416 // dbus daemon not running in multi-account mode
417 return null;
418 }
419 }
420
421 /**
422 * @return the default data directory to be used by signal-cli.
423 */
424 private static File getDefaultConfigPath() {
425 return new File(IOUtils.getDataHomeDir(), "signal-cli");
426 }
427 }