]> nmode's Git Repositories - signal-cli/blobdiff - src/main/java/org/asamk/signal/commands/DaemonCommand.java
Fix TextStyle doc example typo (#1251)
[signal-cli] / src / main / java / org / asamk / signal / commands / DaemonCommand.java
index 726cf26800d87bb9ef3651c65bf3f0dc8b18651e..d32dc69ca809f6f6a7d44f902dde972b933dbaa4 100644 (file)
@@ -5,23 +5,27 @@ import net.sourceforge.argparse4j.inf.Namespace;
 import net.sourceforge.argparse4j.inf.Subparser;
 
 import org.asamk.signal.DbusConfig;
-import org.asamk.signal.JsonReceiveMessageHandler;
-import org.asamk.signal.JsonWriter;
-import org.asamk.signal.JsonWriterImpl;
 import org.asamk.signal.OutputType;
-import org.asamk.signal.OutputWriter;
-import org.asamk.signal.PlainTextWriter;
 import org.asamk.signal.ReceiveMessageHandler;
 import org.asamk.signal.commands.exceptions.CommandException;
 import org.asamk.signal.commands.exceptions.IOErrorException;
 import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
+import org.asamk.signal.commands.exceptions.UserErrorException;
 import org.asamk.signal.dbus.DbusSignalControlImpl;
 import org.asamk.signal.dbus.DbusSignalImpl;
+import org.asamk.signal.http.HttpServerHandler;
+import org.asamk.signal.json.JsonReceiveMessageHandler;
 import org.asamk.signal.jsonrpc.SignalJsonRpcDispatcherHandler;
 import org.asamk.signal.manager.Manager;
 import org.asamk.signal.manager.MultiAccountManager;
+import org.asamk.signal.manager.api.ReceiveConfig;
+import org.asamk.signal.output.JsonWriter;
+import org.asamk.signal.output.JsonWriterImpl;
+import org.asamk.signal.output.OutputWriter;
+import org.asamk.signal.output.PlainTextWriter;
 import org.asamk.signal.util.IOUtils;
 import org.freedesktop.dbus.connections.impl.DBusConnection;
+import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder;
 import org.freedesktop.dbus.exceptions.DBusException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -35,9 +39,8 @@ import java.nio.channels.ServerSocketChannel;
 import java.nio.channels.SocketChannel;
 import java.nio.charset.StandardCharsets;
 import java.util.List;
-import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Consumer;
-import java.util.stream.Collectors;
 
 public class DaemonCommand implements MultiLocalCommand, LocalCommand {
 
@@ -67,6 +70,10 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
                 .nargs("?")
                 .setConst("localhost:7583")
                 .help("Expose a JSON-RPC interface on a TCP socket (default localhost:7583).");
+        subparser.addArgument("--http")
+                .nargs("?")
+                .setConst("localhost:8080")
+                .help("Expose a JSON-RPC interface as http endpoint (default localhost:8080).");
         subparser.addArgument("--no-receive-stdout")
                 .help("Don’t print received messages to stdout.")
                 .action(Arguments.storeTrue());
@@ -77,6 +84,12 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
         subparser.addArgument("--ignore-attachments")
                 .help("Don’t download attachments of received messages.")
                 .action(Arguments.storeTrue());
+        subparser.addArgument("--ignore-stories")
+                .help("Don’t receive story messages from the server.")
+                .action(Arguments.storeTrue());
+        subparser.addArgument("--send-read-receipts")
+                .help("Send read receipts for all incoming data messages (in addition to the default delivery receipts)")
+                .action(Arguments.storeTrue());
     }
 
     @Override
@@ -92,8 +105,10 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
         final var noReceiveStdOut = Boolean.TRUE.equals(ns.getBoolean("no-receive-stdout"));
         final var receiveMode = ns.<ReceiveMode>get("receive-mode");
         final var ignoreAttachments = Boolean.TRUE.equals(ns.getBoolean("ignore-attachments"));
+        final var ignoreStories = Boolean.TRUE.equals(ns.getBoolean("ignore-stories"));
+        final var sendReadReceipts = Boolean.TRUE.equals(ns.getBoolean("send-read-receipts"));
 
-        m.setIgnoreAttachments(ignoreAttachments);
+        m.setReceiveConfig(new ReceiveConfig(ignoreAttachments, ignoreStories, sendReadReceipts));
         addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START);
 
         final Channel inheritedChannel;
@@ -118,6 +133,16 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
             final var serverChannel = IOUtils.bindSocket(address);
             runSocketSingleAccount(m, serverChannel, receiveMode == ReceiveMode.MANUAL);
         }
+        final var httpAddress = ns.getString("http");
+        if (httpAddress != null) {
+            final var address = IOUtils.parseInetSocketAddress(httpAddress);
+            final var handler = new HttpServerHandler(address, m);
+            try {
+                handler.init();
+            } catch (IOException ex) {
+                throw new IOErrorException("Failed to initialize HTTP Server", ex);
+            }
+        }
         final var isDbusSystem = Boolean.TRUE.equals(ns.getBoolean("dbus-system"));
         if (isDbusSystem) {
             runDbusSingleAccount(m, true, receiveMode != ReceiveMode.ON_START);
@@ -127,6 +152,7 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
                 !isDbusSystem
                         && socketFile == null
                         && tcpAddress == null
+                        && httpAddress == null
                         && !(inheritedChannel instanceof ServerSocketChannel)
         )) {
             runDbusSingleAccount(m, false, receiveMode != ReceiveMode.ON_START);
@@ -154,13 +180,16 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
         final var noReceiveStdOut = Boolean.TRUE.equals(ns.getBoolean("no-receive-stdout"));
         final var receiveMode = ns.<ReceiveMode>get("receive-mode");
         final var ignoreAttachments = Boolean.TRUE.equals(ns.getBoolean("ignore-attachments"));
+        final var ignoreStories = Boolean.TRUE.equals(ns.getBoolean("ignore-stories"));
+        final var sendReadReceipts = Boolean.TRUE.equals(ns.getBoolean("send-read-receipts"));
 
-        c.getAccountNumbers().stream().map(c::getManager).filter(Objects::nonNull).forEach(m -> {
-            m.setIgnoreAttachments(ignoreAttachments);
+        final var receiveConfig = new ReceiveConfig(ignoreAttachments, ignoreStories, sendReadReceipts);
+        c.getManagers().forEach(m -> {
+            m.setReceiveConfig(receiveConfig);
             addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START);
         });
         c.addOnManagerAddedHandler(m -> {
-            m.setIgnoreAttachments(ignoreAttachments);
+            m.setReceiveConfig(receiveConfig);
             addDefaultReceiveHandler(m, noReceiveStdOut ? null : outputWriter, receiveMode != ReceiveMode.ON_START);
         });
 
@@ -186,6 +215,16 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
             final var serverChannel = IOUtils.bindSocket(address);
             runSocketMultiAccount(c, serverChannel, receiveMode == ReceiveMode.MANUAL);
         }
+        final var httpAddress = ns.getString("http");
+        if (httpAddress != null) {
+            final var address = IOUtils.parseInetSocketAddress(httpAddress);
+            final var handler = new HttpServerHandler(address, c);
+            try {
+                handler.init();
+            } catch (IOException ex) {
+                throw new IOErrorException("Failed to initialize HTTP Server", ex);
+            }
+        }
         final var isDbusSystem = Boolean.TRUE.equals(ns.getBoolean("dbus-system"));
         if (isDbusSystem) {
             runDbusMultiAccount(c, receiveMode != ReceiveMode.ON_START, true);
@@ -195,6 +234,7 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
                 !isDbusSystem
                         && socketFile == null
                         && tcpAddress == null
+                        && httpAddress == null
                         && !(inheritedChannel instanceof ServerSocketChannel)
         )) {
             runDbusMultiAccount(c, receiveMode != ReceiveMode.ON_START, false);
@@ -235,15 +275,18 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
         });
     }
 
+    private static final AtomicInteger threadNumber = new AtomicInteger(0);
+
     private void runSocket(final ServerSocketChannel serverChannel, Consumer<SocketChannel> socketHandler) {
-        new Thread(() -> {
+        final var thread = new Thread(() -> {
             while (true) {
+                final var connectionId = threadNumber.getAndIncrement();
                 final SocketChannel channel;
                 final String clientString;
                 try {
                     channel = serverChannel.accept();
                     clientString = channel.getRemoteAddress() + " " + IOUtils.getUnixDomainPrincipal(channel);
-                    logger.info("Accepted new client: " + clientString);
+                    logger.info("Accepted new client connection {}: {}", connectionId, clientString);
                 } catch (IOException e) {
                     logger.error("Failed to accept new socket connection", e);
                     synchronized (this) {
@@ -251,16 +294,22 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
                     }
                     break;
                 }
-                new Thread(() -> {
+                final var connectionThread = new Thread(() -> {
                     try (final var c = channel) {
                         socketHandler.accept(c);
-                        logger.info("Connection closed: " + clientString);
                     } catch (IOException e) {
                         logger.warn("Failed to close channel", e);
+                    } catch (Throwable e) {
+                        logger.warn("Connection handler failed, closing connection", e);
                     }
-                }).start();
+                    logger.info("Connection {} closed: {}", connectionId, clientString);
+                });
+                connectionThread.setName("daemon-connection-" + connectionId);
+                connectionThread.start();
             }
-        }).start();
+        });
+        thread.setName("daemon-listener");
+        thread.start();
     }
 
     private SignalJsonRpcDispatcherHandler getSignalJsonRpcDispatcherHandler(
@@ -274,7 +323,7 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
 
     private void runDbusSingleAccount(
             final Manager m, final boolean isDbusSystem, final boolean noReceiveOnStart
-    ) throws UnexpectedErrorException {
+    ) throws CommandException {
         runDbus(isDbusSystem, (conn, objectPath) -> {
             try {
                 exportDbusObject(conn, objectPath, m, noReceiveOnStart).join();
@@ -285,18 +334,16 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
 
     private void runDbusMultiAccount(
             final MultiAccountManager c, final boolean noReceiveOnStart, final boolean isDbusSystem
-    ) throws UnexpectedErrorException {
+    ) throws CommandException {
         runDbus(isDbusSystem, (connection, objectPath) -> {
             final var signalControl = new DbusSignalControlImpl(c, objectPath);
             connection.exportObject(signalControl);
 
             c.addOnManagerAddedHandler(m -> {
                 final var thread = exportMultiAccountManager(connection, m, noReceiveOnStart);
-                if (thread != null) {
-                    try {
-                        thread.join();
-                    } catch (InterruptedException ignored) {
-                    }
+                try {
+                    thread.join();
+                } catch (InterruptedException ignored) {
                 }
             });
             c.addOnManagerRemovedHandler(m -> {
@@ -308,16 +355,12 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
                     }
                 } catch (DBusException ignored) {
                 }
-                connection.unExportObject(path);
             });
 
-            final var initThreads = c.getAccountNumbers()
+            final var initThreads = c.getManagers()
                     .stream()
-                    .map(c::getManager)
-                    .filter(Objects::nonNull)
                     .map(m -> exportMultiAccountManager(connection, m, noReceiveOnStart))
-                    .filter(Objects::nonNull)
-                    .collect(Collectors.toList());
+                    .toList();
 
             for (var t : initThreads) {
                 try {
@@ -330,48 +373,48 @@ public class DaemonCommand implements MultiLocalCommand, LocalCommand {
 
     private void runDbus(
             final boolean isDbusSystem, DbusRunner dbusRunner
-    ) throws UnexpectedErrorException {
+    ) throws CommandException {
         DBusConnection.DBusBusType busType;
         if (isDbusSystem) {
             busType = DBusConnection.DBusBusType.SYSTEM;
         } else {
             busType = DBusConnection.DBusBusType.SESSION;
         }
+        DBusConnection conn;
         try {
-            var conn = DBusConnection.getConnection(busType);
+            conn = DBusConnectionBuilder.forType(busType).build();
             dbusRunner.run(conn, DbusConfig.getObjectPath());
+        } catch (DBusException e) {
+            throw new UnexpectedErrorException("Dbus command failed: " + e.getMessage(), e);
+        } catch (UnsupportedOperationException e) {
+            throw new UserErrorException("Failed to connect to Dbus: " + e.getMessage(), e);
+        }
 
+        try {
             conn.requestBusName(DbusConfig.getBusname());
-
-            logger.info("DBus daemon running on {} bus: {}", busType, DbusConfig.getBusname());
         } catch (DBusException e) {
-            logger.error("Dbus command failed", e);
-            throw new UnexpectedErrorException("Dbus command failed", e);
+            throw new UnexpectedErrorException("Dbus command failed, maybe signal-cli dbus daemon is already running: "
+                    + e.getMessage(), e);
         }
+
+        logger.info("DBus daemon running on {} bus: {}", busType, DbusConfig.getBusname());
     }
 
     private Thread exportMultiAccountManager(
             final DBusConnection conn, final Manager m, final boolean noReceiveOnStart
     ) {
-        try {
-            final var objectPath = DbusConfig.getObjectPath(m.getSelfNumber());
-            return exportDbusObject(conn, objectPath, m, noReceiveOnStart);
-        } catch (DBusException e) {
-            logger.error("Failed to export object", e);
-            return null;
-        }
+        final var objectPath = DbusConfig.getObjectPath(m.getSelfNumber());
+        return exportDbusObject(conn, objectPath, m, noReceiveOnStart);
     }
 
     private Thread exportDbusObject(
             final DBusConnection conn, final String objectPath, final Manager m, final boolean noReceiveOnStart
-    ) throws DBusException {
+    ) {
         final var signal = new DbusSignalImpl(m, conn, objectPath, noReceiveOnStart);
-        conn.exportObject(signal);
         final var initThread = new Thread(signal::initObjects);
+        initThread.setName("dbus-init");
         initThread.start();
 
-        logger.debug("Exported dbus object: " + objectPath);
-
         return initThread;
     }