]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/ReceiveCommand.java
6b2e497e10b3fd8953bf1960275de1fc497f2c7a
[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) {
62 final var jsonWriter = (JsonWriter) outputWriter;
63
64 dbusconnection.addSigHandler(Signal.MessageReceived.class, signal, messageReceived -> {
65 var envelope = new JsonMessageEnvelope(messageReceived);
66 final var object = Map.of("envelope", envelope);
67 jsonWriter.write(object);
68 });
69
70 dbusconnection.addSigHandler(Signal.ReceiptReceived.class, signal, receiptReceived -> {
71 var envelope = new JsonMessageEnvelope(receiptReceived);
72 final var object = Map.of("envelope", envelope);
73 jsonWriter.write(object);
74 });
75
76 dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, signal, syncReceived -> {
77 var envelope = new JsonMessageEnvelope(syncReceived);
78 final var object = Map.of("envelope", envelope);
79 jsonWriter.write(object);
80 });
81 } else {
82 final var writer = (PlainTextWriter) outputWriter;
83
84 dbusconnection.addSigHandler(Signal.MessageReceived.class, signal, messageReceived -> {
85 writer.println("Envelope from: {}", messageReceived.getSender());
86 writer.println("Timestamp: {}", DateUtils.formatTimestamp(messageReceived.getTimestamp()));
87 writer.println("Body: {}", messageReceived.getMessage());
88 if (messageReceived.getGroupId().length > 0) {
89 writer.println("Group info:");
90 writer.indentedWriter()
91 .println("Id: {}", Base64.getEncoder().encodeToString(messageReceived.getGroupId()));
92 }
93 if (messageReceived.getAttachments().size() > 0) {
94 writer.println("Attachments:");
95 for (var attachment : messageReceived.getAttachments()) {
96 writer.println("- Stored plaintext in: {}", attachment);
97 }
98 }
99 writer.println();
100 });
101
102 dbusconnection.addSigHandler(Signal.ReceiptReceived.class, signal, receiptReceived -> {
103 writer.println("Receipt from: {}", receiptReceived.getSender());
104 writer.println("Timestamp: {}", DateUtils.formatTimestamp(receiptReceived.getTimestamp()));
105 });
106
107 dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, signal, syncReceived -> {
108 writer.println("Sync Envelope from: {} to: {}",
109 syncReceived.getSource(),
110 syncReceived.getDestination());
111 writer.println("Timestamp: {}", DateUtils.formatTimestamp(syncReceived.getTimestamp()));
112 writer.println("Body: {}", syncReceived.getMessage());
113 if (syncReceived.getGroupId().length > 0) {
114 writer.println("Group info:");
115 writer.indentedWriter()
116 .println("Id: {}", Base64.getEncoder().encodeToString(syncReceived.getGroupId()));
117 }
118 if (syncReceived.getAttachments().size() > 0) {
119 writer.println("Attachments:");
120 for (var attachment : syncReceived.getAttachments()) {
121 writer.println("- Stored plaintext in: {}", attachment);
122 }
123 }
124 writer.println();
125 });
126 }
127 } catch (DBusException e) {
128 logger.error("Dbus client failed", e);
129 throw new UnexpectedErrorException("Dbus client failed", e);
130 }
131
132 double timeout = ns.getDouble("timeout");
133 long timeoutMilliseconds = timeout < 0 ? 10000 : (long) (timeout * 1000);
134
135 while (true) {
136 try {
137 Thread.sleep(timeoutMilliseconds);
138 } catch (InterruptedException ignored) {
139 break;
140 }
141 if (timeout >= 0) {
142 break;
143 }
144 }
145 }
146
147 @Override
148 public void handleCommand(
149 final Namespace ns, final Manager m, final OutputWriter outputWriter
150 ) throws CommandException {
151 double timeout = ns.getDouble("timeout");
152 boolean ignoreAttachments = Boolean.TRUE.equals(ns.getBoolean("ignore-attachments"));
153 m.setIgnoreAttachments(ignoreAttachments);
154 try {
155 final var handler = outputWriter instanceof JsonWriter ? new JsonReceiveMessageHandler(m,
156 (JsonWriter) outputWriter) : new ReceiveMessageHandler(m, (PlainTextWriter) outputWriter);
157 if (timeout < 0) {
158 m.receiveMessages(handler);
159 } else {
160 m.receiveMessages((long) (timeout * 1000), TimeUnit.MILLISECONDS, handler);
161 }
162 } catch (IOException e) {
163 throw new IOErrorException("Error while receiving messages: " + e.getMessage(), e);
164 }
165 }
166 }