]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/commands/ReceiveCommand.java
e1d1581e554e1883f1a46b6f7bbdadaeb5a129fb
[signal-cli] / src / main / java / org / asamk / signal / commands / ReceiveCommand.java
1 package org.asamk.signal.commands;
2
3 import com.fasterxml.jackson.annotation.JsonAutoDetect;
4 import com.fasterxml.jackson.annotation.PropertyAccessor;
5 import com.fasterxml.jackson.core.JsonGenerator;
6 import com.fasterxml.jackson.databind.ObjectMapper;
7 import com.fasterxml.jackson.databind.node.ObjectNode;
8
9 import net.sourceforge.argparse4j.impl.Arguments;
10 import net.sourceforge.argparse4j.inf.Namespace;
11 import net.sourceforge.argparse4j.inf.Subparser;
12
13 import org.asamk.Signal;
14 import org.asamk.signal.JsonReceiveMessageHandler;
15 import org.asamk.signal.OutputType;
16 import org.asamk.signal.ReceiveMessageHandler;
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.concurrent.TimeUnit;
28
29 import static org.asamk.signal.util.ErrorUtils.handleAssertionError;
30
31 public class ReceiveCommand implements ExtendedDbusCommand, LocalCommand {
32
33 // TODO delete later when "json" variable is removed
34 private final static Logger logger = LoggerFactory.getLogger(ReceiveCommand.class);
35
36 @Override
37 public void attachToSubparser(final Subparser subparser) {
38 subparser.addArgument("-t", "--timeout")
39 .type(double.class)
40 .help("Number of seconds to wait for new messages (negative values disable timeout)");
41 subparser.addArgument("--ignore-attachments")
42 .help("Don’t download attachments of received messages.")
43 .action(Arguments.storeTrue());
44 subparser.addArgument("--json")
45 .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.")
46 .action(Arguments.storeTrue());
47 }
48
49 public int handleCommand(final Namespace ns, final Signal signal, DBusConnection dbusconnection) {
50 final ObjectMapper jsonProcessor;
51
52 boolean inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
53
54 // TODO delete later when "json" variable is removed
55 if (ns.getBoolean("json")) {
56 logger.warn("\"--json\" option has been deprecated, please use the global \"--output=json\" instead.");
57 }
58
59 if (inJson) {
60 jsonProcessor = new ObjectMapper();
61 jsonProcessor.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
62 jsonProcessor.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
63 } else {
64 jsonProcessor = null;
65 }
66 try {
67 dbusconnection.addSigHandler(Signal.MessageReceived.class, messageReceived -> {
68 if (jsonProcessor != null) {
69 JsonMessageEnvelope envelope = new JsonMessageEnvelope(messageReceived);
70 ObjectNode result = jsonProcessor.createObjectNode();
71 result.putPOJO("envelope", envelope);
72 try {
73 jsonProcessor.writeValue(System.out, result);
74 System.out.println();
75 } catch (IOException e) {
76 e.printStackTrace();
77 }
78 } else {
79 System.out.print(String.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
80 messageReceived.getSender(),
81 DateUtils.formatTimestamp(messageReceived.getTimestamp()),
82 messageReceived.getMessage()));
83 if (messageReceived.getGroupId().length > 0) {
84 System.out.println("Group info:");
85 System.out.println(" Id: " + Base64.getEncoder().encodeToString(messageReceived.getGroupId()));
86 }
87 if (messageReceived.getAttachments().size() > 0) {
88 System.out.println("Attachments: ");
89 for (String attachment : messageReceived.getAttachments()) {
90 System.out.println("- Stored plaintext in: " + attachment);
91 }
92 }
93 System.out.println();
94 }
95 });
96
97 dbusconnection.addSigHandler(Signal.ReceiptReceived.class, receiptReceived -> {
98 if (jsonProcessor != null) {
99 JsonMessageEnvelope envelope = new JsonMessageEnvelope(receiptReceived);
100 ObjectNode result = jsonProcessor.createObjectNode();
101 result.putPOJO("envelope", envelope);
102 try {
103 jsonProcessor.writeValue(System.out, result);
104 System.out.println();
105 } catch (IOException e) {
106 e.printStackTrace();
107 }
108 } else {
109 System.out.print(String.format("Receipt from: %s\nTimestamp: %s\n",
110 receiptReceived.getSender(),
111 DateUtils.formatTimestamp(receiptReceived.getTimestamp())));
112 }
113 });
114
115 dbusconnection.addSigHandler(Signal.SyncMessageReceived.class, syncReceived -> {
116 if (jsonProcessor != null) {
117 JsonMessageEnvelope envelope = new JsonMessageEnvelope(syncReceived);
118 ObjectNode result = jsonProcessor.createObjectNode();
119 result.putPOJO("envelope", envelope);
120 try {
121 jsonProcessor.writeValue(System.out, result);
122 System.out.println();
123 } catch (IOException e) {
124 e.printStackTrace();
125 }
126 } else {
127 System.out.print(String.format("Sync Envelope from: %s to: %s\nTimestamp: %s\nBody: %s\n",
128 syncReceived.getSource(),
129 syncReceived.getDestination(),
130 DateUtils.formatTimestamp(syncReceived.getTimestamp()),
131 syncReceived.getMessage()));
132 if (syncReceived.getGroupId().length > 0) {
133 System.out.println("Group info:");
134 System.out.println(" Id: " + Base64.getEncoder().encodeToString(syncReceived.getGroupId()));
135 }
136 if (syncReceived.getAttachments().size() > 0) {
137 System.out.println("Attachments: ");
138 for (String attachment : syncReceived.getAttachments()) {
139 System.out.println("- Stored plaintext in: " + attachment);
140 }
141 }
142 System.out.println();
143 }
144 });
145 } catch (DBusException e) {
146 e.printStackTrace();
147 return 2;
148 }
149 while (true) {
150 try {
151 Thread.sleep(10000);
152 } catch (InterruptedException e) {
153 return 0;
154 }
155 }
156 }
157
158 @Override
159 public int handleCommand(final Namespace ns, final Manager m) {
160 boolean inJson = ns.get("output") == OutputType.JSON || ns.getBoolean("json");
161
162 // TODO delete later when "json" variable is removed
163 if (ns.getBoolean("json")) {
164 logger.warn("\"--json\" option has been deprecated, please use the global \"--output=json\" instead.");
165 }
166
167 double timeout = 5;
168 if (ns.getDouble("timeout") != null) {
169 timeout = ns.getDouble("timeout");
170 }
171 boolean returnOnTimeout = true;
172 if (timeout < 0) {
173 returnOnTimeout = false;
174 timeout = 3600;
175 }
176 boolean ignoreAttachments = ns.getBoolean("ignore_attachments");
177 try {
178 final Manager.ReceiveMessageHandler handler = inJson
179 ? new JsonReceiveMessageHandler(m)
180 : new ReceiveMessageHandler(m);
181 m.receiveMessages((long) (timeout * 1000),
182 TimeUnit.MILLISECONDS,
183 returnOnTimeout,
184 ignoreAttachments,
185 handler);
186 return 0;
187 } catch (IOException e) {
188 System.err.println("Error while receiving messages: " + e.getMessage());
189 return 3;
190 } catch (AssertionError e) {
191 handleAssertionError(e);
192 return 1;
193 }
194 }
195 }