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