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