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