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