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