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