]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/ReceiveCommand.java
Reduce default receive timeout to 1 second
[signal-cli] / src / main / java / org / asamk / signal / commands / ReceiveCommand.java
1 package org.asamk.signal.commands;
2
3 import net.sourceforge.argparse4j.impl.Arguments;
4 import net.sourceforge.argparse4j.inf.Namespace;
5 import net.sourceforge.argparse4j.inf.Subparser;
6
7 import org.asamk.Signal;
8 import org.asamk.signal.JsonReceiveMessageHandler;
9 import org.asamk.signal.JsonWriter;
10 import org.asamk.signal.OutputType;
11 import org.asamk.signal.PlainTextWriterImpl;
12 import org.asamk.signal.ReceiveMessageHandler;
13 import org.asamk.signal.commands.exceptions.CommandException;
14 import org.asamk.signal.commands.exceptions.IOErrorException;
15 import org.asamk.signal.commands.exceptions.UnexpectedErrorException;
16 import org.asamk.signal.json.JsonMessageEnvelope;
17 import org.asamk.signal.manager.Manager;
18 import org.asamk.signal.util.DateUtils;
19 import org.freedesktop.dbus.connections.impl.DBusConnection;
20 import org.freedesktop.dbus.exceptions.DBusException;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import java.io.IOException;
25 import java.util.Base64;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.TimeUnit;
29
30 public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
31
32 private final static Logger logger = LoggerFactory.getLogger(ReceiveCommand.class);
33
34 @Override
35 public void attachToSubparser(final Subparser subparser) {
36 subparser.addArgument("-t", "--timeout")
37 .type(double.class)
38 .setDefault(1.0)
39 .help("Number of seconds to wait for new messages (negative values disable timeout)");
40 subparser.addArgument("--ignore-attachments")
41 .help("Don’t download attachments of received messages.")
42 .action(Arguments.storeTrue());
43 subparser.addArgument("--json")
44 .help("WARNING: This parameter is now deprecated! Please use the global \"--output=json\" option instead.\n\nOutput received messages in json format, one json object per line.")
45 .action(Arguments.storeTrue());
46 }
47
48 @Override
49 public Set<OutputType> getSupportedOutputTypes() {
50 return Set.of(OutputType.PLAIN_TEXT, OutputType.JSON);
51 }
52
53 public void handleCommand(
54 final Namespace ns, final Signal signal, DBusConnection dbusconnection
55 ) throws CommandException {
56 var inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
57
58 // TODO delete later when "json" variable is removed
59 if (ns.getBoolean("json")) {
60 logger.warn("\"--json\" option has been deprecated, please use the global \"--output=json\" instead.");
61 }
62
63 try {
64 if (inJson) {
65 final var jsonWriter = new JsonWriter(System.out);
66
67 dbusconnection.addSigHandler(Signal.MessageReceived.class, messageReceived -> {
68 var envelope = new JsonMessageEnvelope(messageReceived);
69 final var object = Map.of("envelope", envelope);
70 jsonWriter.write(object);
71 });
72
73 dbusconnection.addSigHandler(Signal.ReceiptReceived.class, receiptReceived -> {
74 var envelope = new JsonMessageEnvelope(receiptReceived);
75 final var object = Map.of("envelope", envelope);
76 jsonWriter.write(object);
77 });
78
79 dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, syncReceived -> {
80 var envelope = new JsonMessageEnvelope(syncReceived);
81 final var object = Map.of("envelope", envelope);
82 jsonWriter.write(object);
83 });
84 } else {
85 final var writer = new PlainTextWriterImpl(System.out);
86
87 dbusconnection.addSigHandler(Signal.MessageReceived.class, messageReceived -> {
88 writer.println("Envelope from: {}", messageReceived.getSender());
89 writer.println("Timestamp: {}", DateUtils.formatTimestamp(messageReceived.getTimestamp()));
90 writer.println("Body: {}", messageReceived.getMessage());
91 if (messageReceived.getGroupId().length > 0) {
92 writer.println("Group info:");
93 writer.indentedWriter()
94 .println("Id: {}", Base64.getEncoder().encodeToString(messageReceived.getGroupId()));
95 }
96 if (messageReceived.getAttachments().size() > 0) {
97 writer.println("Attachments:");
98 for (var attachment : messageReceived.getAttachments()) {
99 writer.println("- Stored plaintext in: {}", attachment);
100 }
101 }
102 writer.println();
103 });
104
105 dbusconnection.addSigHandler(Signal.ReceiptReceived.class, receiptReceived -> {
106 writer.println("Receipt from: {}", receiptReceived.getSender());
107 writer.println("Timestamp: {}", DateUtils.formatTimestamp(receiptReceived.getTimestamp()));
108 });
109
110 dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, syncReceived -> {
111 writer.println("Sync Envelope from: {} to: {}",
112 syncReceived.getSource(),
113 syncReceived.getDestination());
114 writer.println("Timestamp: {}", DateUtils.formatTimestamp(syncReceived.getTimestamp()));
115 writer.println("Body: {}", syncReceived.getMessage());
116 if (syncReceived.getGroupId().length > 0) {
117 writer.println("Group info:");
118 writer.indentedWriter()
119 .println("Id: {}", Base64.getEncoder().encodeToString(syncReceived.getGroupId()));
120 }
121 if (syncReceived.getAttachments().size() > 0) {
122 writer.println("Attachments:");
123 for (var attachment : syncReceived.getAttachments()) {
124 writer.println("- Stored plaintext in: {}", attachment);
125 }
126 }
127 writer.println();
128 });
129 }
130 } catch (DBusException e) {
131 logger.error("Dbus client failed", e);
132 throw new UnexpectedErrorException("Dbus client failed");
133 }
134 while (true) {
135 try {
136 Thread.sleep(10000);
137 } catch (InterruptedException ignored) {
138 return;
139 }
140 }
141 }
142
143 @Override
144 public void handleCommand(final Namespace ns, final Manager m) throws CommandException {
145 var inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
146
147 // TODO delete later when "json" variable is removed
148 if (ns.getBoolean("json")) {
149 logger.warn("\"--json\" option has been deprecated, please use the global \"--output=json\" instead.");
150 }
151
152 double timeout = ns.getDouble("timeout");
153 var returnOnTimeout = true;
154 if (timeout < 0) {
155 returnOnTimeout = false;
156 timeout = 3600;
157 }
158 boolean ignoreAttachments = ns.getBoolean("ignore_attachments");
159 try {
160 final var handler = inJson ? new JsonReceiveMessageHandler(m) : new ReceiveMessageHandler(m);
161 m.receiveMessages((long) (timeout * 1000),
162 TimeUnit.MILLISECONDS,
163 returnOnTimeout,
164 ignoreAttachments,
165 handler);
166 } catch (IOException e) {
167 throw new IOErrorException("Error while receiving messages: " + e.getMessage());
168 }
169 }
170 }