]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
Extract utils methods
[signal-cli] / src / main / java / org / asamk / signal / Main.java
1 /*
2 Copyright (C) 2015-2018 AsamK
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package org.asamk.signal;
18
19 import com.fasterxml.jackson.annotation.JsonAutoDetect;
20 import com.fasterxml.jackson.annotation.PropertyAccessor;
21 import com.fasterxml.jackson.core.JsonGenerator;
22 import com.fasterxml.jackson.databind.DeserializationFeature;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.fasterxml.jackson.databind.SerializationFeature;
25 import com.fasterxml.jackson.databind.node.ObjectNode;
26 import net.sourceforge.argparse4j.ArgumentParsers;
27 import net.sourceforge.argparse4j.impl.Arguments;
28 import net.sourceforge.argparse4j.inf.*;
29 import org.apache.http.util.TextUtils;
30 import org.asamk.Signal;
31 import org.asamk.signal.manager.BaseConfig;
32 import org.asamk.signal.manager.Manager;
33 import org.asamk.signal.storage.contacts.ContactInfo;
34 import org.asamk.signal.storage.groups.GroupInfo;
35 import org.asamk.signal.storage.protocol.JsonIdentityKeyStore;
36 import org.asamk.signal.util.DateUtils;
37 import org.asamk.signal.util.Hex;
38 import org.asamk.signal.util.IOUtils;
39 import org.asamk.signal.util.Util;
40 import org.freedesktop.dbus.DBusConnection;
41 import org.freedesktop.dbus.DBusSigHandler;
42 import org.freedesktop.dbus.exceptions.DBusException;
43 import org.freedesktop.dbus.exceptions.DBusExecutionException;
44 import org.whispersystems.libsignal.InvalidKeyException;
45 import org.whispersystems.libsignal.util.guava.Optional;
46 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
47 import org.whispersystems.signalservice.api.messages.*;
48 import org.whispersystems.signalservice.api.messages.calls.*;
49 import org.whispersystems.signalservice.api.messages.multidevice.*;
50 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
51 import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions;
52 import org.whispersystems.signalservice.api.push.exceptions.NetworkFailureException;
53 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
54 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
55 import org.whispersystems.signalservice.internal.push.LockedException;
56 import org.whispersystems.signalservice.internal.util.Base64;
57
58 import java.io.File;
59 import java.io.IOException;
60 import java.net.URI;
61 import java.net.URISyntaxException;
62 import java.nio.charset.Charset;
63 import java.security.Security;
64 import java.util.ArrayList;
65 import java.util.List;
66 import java.util.Locale;
67 import java.util.Map;
68 import java.util.concurrent.TimeUnit;
69 import java.util.concurrent.TimeoutException;
70
71 public class Main {
72
73 private static final String SIGNAL_BUSNAME = "org.asamk.Signal";
74 private static final String SIGNAL_OBJECTPATH = "/org/asamk/Signal";
75
76 public static void main(String[] args) {
77 // Workaround for BKS truststore
78 Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);
79
80 Namespace ns = parseArgs(args);
81 if (ns == null) {
82 System.exit(1);
83 }
84
85 int res = handleCommands(ns);
86 System.exit(res);
87 }
88
89 private static int handleCommands(Namespace ns) {
90 final String username = ns.getString("username");
91 Manager m;
92 Signal ts;
93 DBusConnection dBusConn = null;
94 try {
95 if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
96 try {
97 m = null;
98 int busType;
99 if (ns.getBoolean("dbus_system")) {
100 busType = DBusConnection.SYSTEM;
101 } else {
102 busType = DBusConnection.SESSION;
103 }
104 dBusConn = DBusConnection.getConnection(busType);
105 ts = dBusConn.getRemoteObject(
106 SIGNAL_BUSNAME, SIGNAL_OBJECTPATH,
107 Signal.class);
108 } catch (UnsatisfiedLinkError e) {
109 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
110 return 1;
111 } catch (DBusException e) {
112 e.printStackTrace();
113 if (dBusConn != null) {
114 dBusConn.disconnect();
115 }
116 return 3;
117 }
118 } else {
119 String settingsPath = ns.getString("config");
120 if (TextUtils.isEmpty(settingsPath)) {
121 settingsPath = System.getProperty("user.home") + "/.config/signal";
122 if (!new File(settingsPath).exists()) {
123 String legacySettingsPath = System.getProperty("user.home") + "/.config/textsecure";
124 if (new File(legacySettingsPath).exists()) {
125 settingsPath = legacySettingsPath;
126 }
127 }
128 }
129
130 m = new Manager(username, settingsPath);
131 ts = m;
132 try {
133 m.init();
134 } catch (Exception e) {
135 System.err.println("Error loading state file: " + e.getMessage());
136 return 2;
137 }
138 }
139
140 switch (ns.getString("command")) {
141 case "register":
142 if (dBusConn != null) {
143 System.err.println("register is not yet implemented via dbus");
144 return 1;
145 }
146 try {
147 m.register(ns.getBoolean("voice"));
148 } catch (IOException e) {
149 System.err.println("Request verify error: " + e.getMessage());
150 return 3;
151 }
152 break;
153 case "unregister":
154 if (dBusConn != null) {
155 System.err.println("unregister is not yet implemented via dbus");
156 return 1;
157 }
158 if (!m.isRegistered()) {
159 System.err.println("User is not registered.");
160 return 1;
161 }
162 try {
163 m.unregister();
164 } catch (IOException e) {
165 System.err.println("Unregister error: " + e.getMessage());
166 return 3;
167 }
168 break;
169 case "updateAccount":
170 if (dBusConn != null) {
171 System.err.println("updateAccount is not yet implemented via dbus");
172 return 1;
173 }
174 if (!m.isRegistered()) {
175 System.err.println("User is not registered.");
176 return 1;
177 }
178 try {
179 m.updateAccountAttributes();
180 } catch (IOException e) {
181 System.err.println("UpdateAccount error: " + e.getMessage());
182 return 3;
183 }
184 break;
185 case "setPin":
186 if (dBusConn != null) {
187 System.err.println("setPin is not yet implemented via dbus");
188 return 1;
189 }
190 if (!m.isRegistered()) {
191 System.err.println("User is not registered.");
192 return 1;
193 }
194 try {
195 String registrationLockPin = ns.getString("registrationLockPin");
196 m.setRegistrationLockPin(Optional.of(registrationLockPin));
197 } catch (IOException e) {
198 System.err.println("Set pin error: " + e.getMessage());
199 return 3;
200 }
201 break;
202 case "removePin":
203 if (dBusConn != null) {
204 System.err.println("removePin is not yet implemented via dbus");
205 return 1;
206 }
207 if (!m.isRegistered()) {
208 System.err.println("User is not registered.");
209 return 1;
210 }
211 try {
212 m.setRegistrationLockPin(Optional.<String>absent());
213 } catch (IOException e) {
214 System.err.println("Remove pin error: " + e.getMessage());
215 return 3;
216 }
217 break;
218 case "verify":
219 if (dBusConn != null) {
220 System.err.println("verify is not yet implemented via dbus");
221 return 1;
222 }
223 if (!m.userHasKeys()) {
224 System.err.println("User has no keys, first call register.");
225 return 1;
226 }
227 if (m.isRegistered()) {
228 System.err.println("User registration is already verified");
229 return 1;
230 }
231 try {
232 String verificationCode = ns.getString("verificationCode");
233 String pin = ns.getString("pin");
234 m.verifyAccount(verificationCode, pin);
235 } catch (LockedException e) {
236 System.err.println("Verification failed! This number is locked with a pin. Hours remaining until reset: " + (e.getTimeRemaining() / 1000 / 60 / 60));
237 System.err.println("Use '--pin PIN_CODE' to specify the registration lock PIN");
238 return 3;
239 } catch (IOException e) {
240 System.err.println("Verify error: " + e.getMessage());
241 return 3;
242 }
243 break;
244 case "link":
245 if (dBusConn != null) {
246 System.err.println("link is not yet implemented via dbus");
247 return 1;
248 }
249
250 String deviceName = ns.getString("name");
251 if (deviceName == null) {
252 deviceName = "cli";
253 }
254 try {
255 System.out.println(m.getDeviceLinkUri());
256 m.finishDeviceLink(deviceName);
257 System.out.println("Associated with: " + m.getUsername());
258 } catch (TimeoutException e) {
259 System.err.println("Link request timed out, please try again.");
260 return 3;
261 } catch (IOException e) {
262 System.err.println("Link request error: " + e.getMessage());
263 return 3;
264 } catch (AssertionError e) {
265 handleAssertionError(e);
266 return 1;
267 } catch (InvalidKeyException e) {
268 e.printStackTrace();
269 return 2;
270 } catch (UserAlreadyExists e) {
271 System.err.println("The user " + e.getUsername() + " already exists\nDelete \"" + e.getFileName() + "\" before trying again.");
272 return 1;
273 }
274 break;
275 case "addDevice":
276 if (dBusConn != null) {
277 System.err.println("link is not yet implemented via dbus");
278 return 1;
279 }
280 if (!m.isRegistered()) {
281 System.err.println("User is not registered.");
282 return 1;
283 }
284 try {
285 m.addDeviceLink(new URI(ns.getString("uri")));
286 } catch (IOException e) {
287 e.printStackTrace();
288 return 3;
289 } catch (InvalidKeyException | URISyntaxException e) {
290 e.printStackTrace();
291 return 2;
292 } catch (AssertionError e) {
293 handleAssertionError(e);
294 return 1;
295 }
296 break;
297 case "listDevices":
298 if (dBusConn != null) {
299 System.err.println("listDevices is not yet implemented via dbus");
300 return 1;
301 }
302 if (!m.isRegistered()) {
303 System.err.println("User is not registered.");
304 return 1;
305 }
306 try {
307 List<DeviceInfo> devices = m.getLinkedDevices();
308 for (DeviceInfo d : devices) {
309 System.out.println("Device " + d.getId() + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
310 System.out.println(" Name: " + d.getName());
311 System.out.println(" Created: " + DateUtils.formatTimestamp(d.getCreated()));
312 System.out.println(" Last seen: " + DateUtils.formatTimestamp(d.getLastSeen()));
313 }
314 } catch (IOException e) {
315 e.printStackTrace();
316 return 3;
317 }
318 break;
319 case "removeDevice":
320 if (dBusConn != null) {
321 System.err.println("removeDevice is not yet implemented via dbus");
322 return 1;
323 }
324 if (!m.isRegistered()) {
325 System.err.println("User is not registered.");
326 return 1;
327 }
328 try {
329 int deviceId = ns.getInt("deviceId");
330 m.removeLinkedDevices(deviceId);
331 } catch (IOException e) {
332 e.printStackTrace();
333 return 3;
334 }
335 break;
336 case "send":
337 if (dBusConn == null && !m.isRegistered()) {
338 System.err.println("User is not registered.");
339 return 1;
340 }
341
342 if (ns.getBoolean("endsession")) {
343 if (ns.getList("recipient") == null) {
344 System.err.println("No recipients given");
345 System.err.println("Aborting sending.");
346 return 1;
347 }
348 try {
349 ts.sendEndSessionMessage(ns.<String>getList("recipient"));
350 } catch (IOException e) {
351 handleIOException(e);
352 return 3;
353 } catch (EncapsulatedExceptions e) {
354 handleEncapsulatedExceptions(e);
355 return 3;
356 } catch (AssertionError e) {
357 handleAssertionError(e);
358 return 1;
359 } catch (DBusExecutionException e) {
360 handleDBusExecutionException(e);
361 return 1;
362 }
363 } else {
364 String messageText = ns.getString("message");
365 if (messageText == null) {
366 try {
367 messageText = IOUtils.readAll(System.in, Charset.defaultCharset());
368 } catch (IOException e) {
369 System.err.println("Failed to read message from stdin: " + e.getMessage());
370 System.err.println("Aborting sending.");
371 return 1;
372 }
373 }
374
375 try {
376 List<String> attachments = ns.getList("attachment");
377 if (attachments == null) {
378 attachments = new ArrayList<>();
379 }
380 if (ns.getString("group") != null) {
381 byte[] groupId = decodeGroupId(ns.getString("group"));
382 ts.sendGroupMessage(messageText, attachments, groupId);
383 } else {
384 ts.sendMessage(messageText, attachments, ns.<String>getList("recipient"));
385 }
386 } catch (IOException e) {
387 handleIOException(e);
388 return 3;
389 } catch (EncapsulatedExceptions e) {
390 handleEncapsulatedExceptions(e);
391 return 3;
392 } catch (AssertionError e) {
393 handleAssertionError(e);
394 return 1;
395 } catch (GroupNotFoundException e) {
396 handleGroupNotFoundException(e);
397 return 1;
398 } catch (NotAGroupMemberException e) {
399 handleNotAGroupMemberException(e);
400 return 1;
401 } catch (AttachmentInvalidException e) {
402 System.err.println("Failed to add attachment: " + e.getMessage());
403 System.err.println("Aborting sending.");
404 return 1;
405 } catch (DBusExecutionException e) {
406 handleDBusExecutionException(e);
407 return 1;
408 }
409 }
410
411 break;
412 case "receive":
413 if (dBusConn != null) {
414 try {
415 dBusConn.addSigHandler(Signal.MessageReceived.class, new DBusSigHandler<Signal.MessageReceived>() {
416 @Override
417 public void handle(Signal.MessageReceived s) {
418 System.out.print(String.format("Envelope from: %s\nTimestamp: %s\nBody: %s\n",
419 s.getSender(), DateUtils.formatTimestamp(s.getTimestamp()), s.getMessage()));
420 if (s.getGroupId().length > 0) {
421 System.out.println("Group info:");
422 System.out.println(" Id: " + Base64.encodeBytes(s.getGroupId()));
423 }
424 if (s.getAttachments().size() > 0) {
425 System.out.println("Attachments: ");
426 for (String attachment : s.getAttachments()) {
427 System.out.println("- Stored plaintext in: " + attachment);
428 }
429 }
430 System.out.println();
431 }
432 });
433 dBusConn.addSigHandler(Signal.ReceiptReceived.class, new DBusSigHandler<Signal.ReceiptReceived>() {
434 @Override
435 public void handle(Signal.ReceiptReceived s) {
436 System.out.print(String.format("Receipt from: %s\nTimestamp: %s\n",
437 s.getSender(), DateUtils.formatTimestamp(s.getTimestamp())));
438 }
439 });
440 } catch (UnsatisfiedLinkError e) {
441 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
442 return 1;
443 } catch (DBusException e) {
444 e.printStackTrace();
445 return 1;
446 }
447 while (true) {
448 try {
449 Thread.sleep(10000);
450 } catch (InterruptedException e) {
451 return 0;
452 }
453 }
454 }
455 if (!m.isRegistered()) {
456 System.err.println("User is not registered.");
457 return 1;
458 }
459 double timeout = 5;
460 if (ns.getDouble("timeout") != null) {
461 timeout = ns.getDouble("timeout");
462 }
463 boolean returnOnTimeout = true;
464 if (timeout < 0) {
465 returnOnTimeout = false;
466 timeout = 3600;
467 }
468 boolean ignoreAttachments = ns.getBoolean("ignore_attachments");
469 try {
470 final Manager.ReceiveMessageHandler handler = ns.getBoolean("json") ? new JsonReceiveMessageHandler(m) : new ReceiveMessageHandler(m);
471 m.receiveMessages((long) (timeout * 1000), TimeUnit.MILLISECONDS, returnOnTimeout, ignoreAttachments, handler);
472 } catch (IOException e) {
473 System.err.println("Error while receiving messages: " + e.getMessage());
474 return 3;
475 } catch (AssertionError e) {
476 handleAssertionError(e);
477 return 1;
478 }
479 break;
480 case "quitGroup":
481 if (dBusConn != null) {
482 System.err.println("quitGroup is not yet implemented via dbus");
483 return 1;
484 }
485 if (!m.isRegistered()) {
486 System.err.println("User is not registered.");
487 return 1;
488 }
489
490 try {
491 m.sendQuitGroupMessage(decodeGroupId(ns.getString("group")));
492 } catch (IOException e) {
493 handleIOException(e);
494 return 3;
495 } catch (EncapsulatedExceptions e) {
496 handleEncapsulatedExceptions(e);
497 return 3;
498 } catch (AssertionError e) {
499 handleAssertionError(e);
500 return 1;
501 } catch (GroupNotFoundException e) {
502 handleGroupNotFoundException(e);
503 return 1;
504 } catch (NotAGroupMemberException e) {
505 handleNotAGroupMemberException(e);
506 return 1;
507 }
508
509 break;
510 case "updateGroup":
511 if (dBusConn == null && !m.isRegistered()) {
512 System.err.println("User is not registered.");
513 return 1;
514 }
515
516 try {
517 byte[] groupId = null;
518 if (ns.getString("group") != null) {
519 groupId = decodeGroupId(ns.getString("group"));
520 }
521 if (groupId == null) {
522 groupId = new byte[0];
523 }
524 String groupName = ns.getString("name");
525 if (groupName == null) {
526 groupName = "";
527 }
528 List<String> groupMembers = ns.getList("member");
529 if (groupMembers == null) {
530 groupMembers = new ArrayList<>();
531 }
532 String groupAvatar = ns.getString("avatar");
533 if (groupAvatar == null) {
534 groupAvatar = "";
535 }
536 byte[] newGroupId = ts.updateGroup(groupId, groupName, groupMembers, groupAvatar);
537 if (groupId.length != newGroupId.length) {
538 System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" …");
539 }
540 } catch (IOException e) {
541 handleIOException(e);
542 return 3;
543 } catch (AttachmentInvalidException e) {
544 System.err.println("Failed to add avatar attachment for group\": " + e.getMessage());
545 System.err.println("Aborting sending.");
546 return 1;
547 } catch (GroupNotFoundException e) {
548 handleGroupNotFoundException(e);
549 return 1;
550 } catch (NotAGroupMemberException e) {
551 handleNotAGroupMemberException(e);
552 return 1;
553 } catch (EncapsulatedExceptions e) {
554 handleEncapsulatedExceptions(e);
555 return 3;
556 }
557
558 break;
559 case "listGroups":
560 if (dBusConn != null) {
561 System.err.println("listGroups is not yet implemented via dbus");
562 return 1;
563 }
564 if (!m.isRegistered()) {
565 System.err.println("User is not registered.");
566 return 1;
567 }
568
569 List<GroupInfo> groups = m.getGroups();
570 boolean detailed = ns.getBoolean("detailed");
571
572 for (GroupInfo group : groups) {
573 printGroup(group, detailed);
574 }
575 break;
576 case "listIdentities":
577 if (dBusConn != null) {
578 System.err.println("listIdentities is not yet implemented via dbus");
579 return 1;
580 }
581 if (!m.isRegistered()) {
582 System.err.println("User is not registered.");
583 return 1;
584 }
585 if (ns.get("number") == null) {
586 for (Map.Entry<String, List<JsonIdentityKeyStore.Identity>> keys : m.getIdentities().entrySet()) {
587 for (JsonIdentityKeyStore.Identity id : keys.getValue()) {
588 printIdentityFingerprint(m, keys.getKey(), id);
589 }
590 }
591 } else {
592 String number = ns.getString("number");
593 for (JsonIdentityKeyStore.Identity id : m.getIdentities(number)) {
594 printIdentityFingerprint(m, number, id);
595 }
596 }
597 break;
598 case "trust":
599 if (dBusConn != null) {
600 System.err.println("trust is not yet implemented via dbus");
601 return 1;
602 }
603 if (!m.isRegistered()) {
604 System.err.println("User is not registered.");
605 return 1;
606 }
607 String number = ns.getString("number");
608 if (ns.getBoolean("trust_all_known_keys")) {
609 boolean res = m.trustIdentityAllKeys(number);
610 if (!res) {
611 System.err.println("Failed to set the trust for this number, make sure the number is correct.");
612 return 1;
613 }
614 } else {
615 String fingerprint = ns.getString("verified_fingerprint");
616 if (fingerprint != null) {
617 fingerprint = fingerprint.replaceAll(" ", "");
618 if (fingerprint.length() == 66) {
619 byte[] fingerprintBytes;
620 try {
621 fingerprintBytes = Hex.toByteArray(fingerprint.toLowerCase(Locale.ROOT));
622 } catch (Exception e) {
623 System.err.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters.");
624 return 1;
625 }
626 boolean res = m.trustIdentityVerified(number, fingerprintBytes);
627 if (!res) {
628 System.err.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct.");
629 return 1;
630 }
631 } else if (fingerprint.length() == 60) {
632 boolean res = m.trustIdentityVerifiedSafetyNumber(number, fingerprint);
633 if (!res) {
634 System.err.println("Failed to set the trust for the safety number of this phone number, make sure the phone number and the safety number are correct.");
635 return 1;
636 }
637 } else {
638 System.err.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number");
639 return 1;
640 }
641 } else {
642 System.err.println("You need to specify the fingerprint you have verified with -v FINGERPRINT");
643 return 1;
644 }
645 }
646 break;
647 case "daemon":
648 if (dBusConn != null) {
649 System.err.println("Stop it.");
650 return 1;
651 }
652 if (!m.isRegistered()) {
653 System.err.println("User is not registered.");
654 return 1;
655 }
656 DBusConnection conn = null;
657 try {
658 try {
659 int busType;
660 if (ns.getBoolean("system")) {
661 busType = DBusConnection.SYSTEM;
662 } else {
663 busType = DBusConnection.SESSION;
664 }
665 conn = DBusConnection.getConnection(busType);
666 conn.exportObject(SIGNAL_OBJECTPATH, m);
667 conn.requestBusName(SIGNAL_BUSNAME);
668 } catch (UnsatisfiedLinkError e) {
669 System.err.println("Missing native library dependency for dbus service: " + e.getMessage());
670 return 1;
671 } catch (DBusException e) {
672 e.printStackTrace();
673 return 2;
674 }
675 ignoreAttachments = ns.getBoolean("ignore_attachments");
676 try {
677 m.receiveMessages(1, TimeUnit.HOURS, false, ignoreAttachments, ns.getBoolean("json") ? new JsonDbusReceiveMessageHandler(m, conn) : new DbusReceiveMessageHandler(m, conn));
678 } catch (IOException e) {
679 System.err.println("Error while receiving messages: " + e.getMessage());
680 return 3;
681 } catch (AssertionError e) {
682 handleAssertionError(e);
683 return 1;
684 }
685 } finally {
686 if (conn != null) {
687 conn.disconnect();
688 }
689 }
690
691 break;
692 }
693 return 0;
694 } finally {
695 if (dBusConn != null) {
696 dBusConn.disconnect();
697 }
698 }
699 }
700
701 private static void printIdentityFingerprint(Manager m, String theirUsername, JsonIdentityKeyStore.Identity theirId) {
702 String digits = Util.formatSafetyNumber(m.computeSafetyNumber(theirUsername, theirId.getIdentityKey()));
703 System.out.println(String.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername,
704 theirId.getTrustLevel(), theirId.getDateAdded(), Hex.toStringCondensed(theirId.getFingerprint()), digits));
705 }
706
707 private static void printGroup(GroupInfo group, boolean detailed) {
708 if (detailed) {
709 System.out.println(String.format("Id: %s Name: %s Active: %s Members: %s",
710 Base64.encodeBytes(group.groupId), group.name, group.active, group.members));
711 } else {
712 System.out.println(String.format("Id: %s Name: %s Active: %s", Base64.encodeBytes(group.groupId),
713 group.name, group.active));
714 }
715 }
716
717 private static void handleGroupNotFoundException(GroupNotFoundException e) {
718 System.err.println("Failed to send to group: " + e.getMessage());
719 System.err.println("Aborting sending.");
720 }
721
722 private static void handleNotAGroupMemberException(NotAGroupMemberException e) {
723 System.err.println("Failed to send to group: " + e.getMessage());
724 System.err.println("Update the group on another device to readd the user to this group.");
725 System.err.println("Aborting sending.");
726 }
727
728 private static void handleDBusExecutionException(DBusExecutionException e) {
729 System.err.println("Cannot connect to dbus: " + e.getMessage());
730 System.err.println("Aborting.");
731 }
732
733 private static byte[] decodeGroupId(String groupId) {
734 try {
735 return Base64.decode(groupId);
736 } catch (IOException e) {
737 System.err.println("Failed to decode groupId (must be base64) \"" + groupId + "\": " + e.getMessage());
738 System.err.println("Aborting sending.");
739 System.exit(1);
740 return null;
741 }
742 }
743
744 private static Namespace parseArgs(String[] args) {
745 ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
746 .build()
747 .defaultHelp(true)
748 .description("Commandline interface for Signal.")
749 .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);
750
751 parser.addArgument("-v", "--version")
752 .help("Show package version.")
753 .action(Arguments.version());
754 parser.addArgument("--config")
755 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
756
757 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
758 mut.addArgument("-u", "--username")
759 .help("Specify your phone number, that will be used for verification.");
760 mut.addArgument("--dbus")
761 .help("Make request via user dbus.")
762 .action(Arguments.storeTrue());
763 mut.addArgument("--dbus-system")
764 .help("Make request via system dbus.")
765 .action(Arguments.storeTrue());
766
767 Subparsers subparsers = parser.addSubparsers()
768 .title("subcommands")
769 .dest("command")
770 .description("valid subcommands")
771 .help("additional help");
772
773 Subparser parserLink = subparsers.addParser("link");
774 parserLink.addArgument("-n", "--name")
775 .help("Specify a name to describe this new device.");
776
777 Subparser parserAddDevice = subparsers.addParser("addDevice");
778 parserAddDevice.addArgument("--uri")
779 .required(true)
780 .help("Specify the uri contained in the QR code shown by the new device.");
781
782 Subparser parserDevices = subparsers.addParser("listDevices");
783
784 Subparser parserRemoveDevice = subparsers.addParser("removeDevice");
785 parserRemoveDevice.addArgument("-d", "--deviceId")
786 .type(int.class)
787 .required(true)
788 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
789
790 Subparser parserRegister = subparsers.addParser("register");
791 parserRegister.addArgument("-v", "--voice")
792 .help("The verification should be done over voice, not sms.")
793 .action(Arguments.storeTrue());
794
795 Subparser parserUnregister = subparsers.addParser("unregister");
796 parserUnregister.help("Unregister the current device from the signal server.");
797
798 Subparser parserUpdateAccount = subparsers.addParser("updateAccount");
799 parserUpdateAccount.help("Update the account attributes on the signal server.");
800
801 Subparser parserSetPin = subparsers.addParser("setPin");
802 parserSetPin.addArgument("registrationLockPin")
803 .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)");
804
805 Subparser parserRemovePin = subparsers.addParser("removePin");
806
807 Subparser parserVerify = subparsers.addParser("verify");
808 parserVerify.addArgument("verificationCode")
809 .help("The verification code you received via sms or voice call.");
810 parserVerify.addArgument("-p", "--pin")
811 .help("The registration lock PIN, that was set by the user (Optional)");
812
813 Subparser parserSend = subparsers.addParser("send");
814 parserSend.addArgument("-g", "--group")
815 .help("Specify the recipient group ID.");
816 parserSend.addArgument("recipient")
817 .help("Specify the recipients' phone number.")
818 .nargs("*");
819 parserSend.addArgument("-m", "--message")
820 .help("Specify the message, if missing standard input is used.");
821 parserSend.addArgument("-a", "--attachment")
822 .nargs("*")
823 .help("Add file as attachment");
824 parserSend.addArgument("-e", "--endsession")
825 .help("Clear session state and send end session message.")
826 .action(Arguments.storeTrue());
827
828 Subparser parserLeaveGroup = subparsers.addParser("quitGroup");
829 parserLeaveGroup.addArgument("-g", "--group")
830 .required(true)
831 .help("Specify the recipient group ID.");
832
833 Subparser parserUpdateGroup = subparsers.addParser("updateGroup");
834 parserUpdateGroup.addArgument("-g", "--group")
835 .help("Specify the recipient group ID.");
836 parserUpdateGroup.addArgument("-n", "--name")
837 .help("Specify the new group name.");
838 parserUpdateGroup.addArgument("-a", "--avatar")
839 .help("Specify a new group avatar image file");
840 parserUpdateGroup.addArgument("-m", "--member")
841 .nargs("*")
842 .help("Specify one or more members to add to the group");
843
844 Subparser parserListGroups = subparsers.addParser("listGroups");
845 parserListGroups.addArgument("-d", "--detailed").action(Arguments.storeTrue())
846 .help("List members of each group");
847 parserListGroups.help("List group name and ids");
848
849 Subparser parserListIdentities = subparsers.addParser("listIdentities");
850 parserListIdentities.addArgument("-n", "--number")
851 .help("Only show identity keys for the given phone number.");
852
853 Subparser parserTrust = subparsers.addParser("trust");
854 parserTrust.addArgument("number")
855 .help("Specify the phone number, for which to set the trust.")
856 .required(true);
857 MutuallyExclusiveGroup mutTrust = parserTrust.addMutuallyExclusiveGroup();
858 mutTrust.addArgument("-a", "--trust-all-known-keys")
859 .help("Trust all known keys of this user, only use this for testing.")
860 .action(Arguments.storeTrue());
861 mutTrust.addArgument("-v", "--verified-fingerprint")
862 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
863
864 Subparser parserReceive = subparsers.addParser("receive");
865 parserReceive.addArgument("-t", "--timeout")
866 .type(double.class)
867 .help("Number of seconds to wait for new messages (negative values disable timeout)");
868 parserReceive.addArgument("--ignore-attachments")
869 .help("Don’t download attachments of received messages.")
870 .action(Arguments.storeTrue());
871 parserReceive.addArgument("--json")
872 .help("Output received messages in json format, one json object per line.")
873 .action(Arguments.storeTrue());
874
875 Subparser parserDaemon = subparsers.addParser("daemon");
876 parserDaemon.addArgument("--system")
877 .action(Arguments.storeTrue())
878 .help("Use DBus system bus instead of user bus.");
879 parserDaemon.addArgument("--ignore-attachments")
880 .help("Don’t download attachments of received messages.")
881 .action(Arguments.storeTrue());
882 parserDaemon.addArgument("--json")
883 .help("Output received messages in json format, one json object per line.")
884 .action(Arguments.storeTrue());
885
886 try {
887 Namespace ns = parser.parseArgs(args);
888 if ("link".equals(ns.getString("command"))) {
889 if (ns.getString("username") != null) {
890 parser.printUsage();
891 System.err.println("You cannot specify a username (phone number) when linking");
892 System.exit(2);
893 }
894 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
895 if (ns.getString("username") == null) {
896 parser.printUsage();
897 System.err.println("You need to specify a username (phone number)");
898 System.exit(2);
899 }
900 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"))) {
901 System.err.println("Invalid username (phone number), make sure you include the country code.");
902 System.exit(2);
903 }
904 }
905 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
906 System.err.println("You cannot specify recipients by phone number and groups a the same time");
907 System.exit(2);
908 }
909 return ns;
910 } catch (ArgumentParserException e) {
911 parser.handleError(e);
912 return null;
913 }
914 }
915
916 private static void handleAssertionError(AssertionError e) {
917 System.err.println("Failed to send/receive message (Assertion): " + e.getMessage());
918 e.printStackTrace();
919 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
920 }
921
922 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e) {
923 System.err.println("Failed to send (some) messages:");
924 for (NetworkFailureException n : e.getNetworkExceptions()) {
925 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
926 }
927 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
928 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
929 }
930 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
931 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
932 }
933 }
934
935 private static void handleIOException(IOException e) {
936 System.err.println("Failed to send message: " + e.getMessage());
937 }
938
939 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
940
941 final Manager m;
942
943 ReceiveMessageHandler(Manager m) {
944 this.m = m;
945 }
946
947 @Override
948 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
949 SignalServiceAddress source = envelope.getSourceAddress();
950 ContactInfo sourceContact = m.getContact(source.getNumber());
951 System.out.println(String.format("Envelope from: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getNumber(), envelope.getSourceDevice()));
952 if (source.getRelay().isPresent()) {
953 System.out.println("Relayed by: " + source.getRelay().get());
954 }
955 System.out.println("Timestamp: " + DateUtils.formatTimestamp(envelope.getTimestamp()));
956 if (envelope.isUnidentifiedSender()) {
957 System.out.println("Sent by unidentified/sealed sender");
958 }
959
960 if (envelope.isReceipt()) {
961 System.out.println("Got receipt.");
962 } else if (envelope.isSignalMessage() | envelope.isPreKeySignalMessage()) {
963 if (exception != null) {
964 if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
965 org.whispersystems.libsignal.UntrustedIdentityException e = (org.whispersystems.libsignal.UntrustedIdentityException) exception;
966 System.out.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
967 System.out.println("Use 'signal-cli -u " + m.getUsername() + " listIdentities -n " + e.getName() + "', verify the key and run 'signal-cli -u " + m.getUsername() + " trust -v \"FINGER_PRINT\" " + e.getName() + "' to mark it as trusted");
968 System.out.println("If you don't care about security, use 'signal-cli -u " + m.getUsername() + " trust -a " + e.getName() + "' to trust it without verification");
969 } else {
970 System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass().getSimpleName() + ")");
971 }
972 }
973 if (content == null) {
974 System.out.println("Failed to decrypt message.");
975 } else {
976 if (content.getDataMessage().isPresent()) {
977 SignalServiceDataMessage message = content.getDataMessage().get();
978 handleSignalServiceDataMessage(message);
979 }
980 if (content.getSyncMessage().isPresent()) {
981 System.out.println("Received a sync message");
982 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
983
984 if (syncMessage.getContacts().isPresent()) {
985 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
986 if (contactsMessage.isComplete()) {
987 System.out.println("Received complete sync contacts");
988 } else {
989 System.out.println("Received sync contacts");
990 }
991 printAttachment(contactsMessage.getContactsStream());
992 }
993 if (syncMessage.getGroups().isPresent()) {
994 System.out.println("Received sync groups");
995 printAttachment(syncMessage.getGroups().get());
996 }
997 if (syncMessage.getRead().isPresent()) {
998 System.out.println("Received sync read messages list");
999 for (ReadMessage rm : syncMessage.getRead().get()) {
1000 ContactInfo fromContact = m.getContact(rm.getSender());
1001 System.out.println("From: " + (fromContact == null ? "" : "“" + fromContact.name + "” ") + rm.getSender() + " Message timestamp: " + DateUtils.formatTimestamp(rm.getTimestamp()));
1002 }
1003 }
1004 if (syncMessage.getRequest().isPresent()) {
1005 System.out.println("Received sync request");
1006 if (syncMessage.getRequest().get().isContactsRequest()) {
1007 System.out.println(" - contacts request");
1008 }
1009 if (syncMessage.getRequest().get().isGroupsRequest()) {
1010 System.out.println(" - groups request");
1011 }
1012 }
1013 if (syncMessage.getSent().isPresent()) {
1014 System.out.println("Received sync sent message");
1015 final SentTranscriptMessage sentTranscriptMessage = syncMessage.getSent().get();
1016 String to;
1017 if (sentTranscriptMessage.getDestination().isPresent()) {
1018 String dest = sentTranscriptMessage.getDestination().get();
1019 ContactInfo destContact = m.getContact(dest);
1020 to = (destContact == null ? "" : "“" + destContact.name + "” ") + dest;
1021 } else {
1022 to = "Unknown";
1023 }
1024 System.out.println("To: " + to + " , Message timestamp: " + DateUtils.formatTimestamp(sentTranscriptMessage.getTimestamp()));
1025 if (sentTranscriptMessage.getExpirationStartTimestamp() > 0) {
1026 System.out.println("Expiration started at: " + DateUtils.formatTimestamp(sentTranscriptMessage.getExpirationStartTimestamp()));
1027 }
1028 SignalServiceDataMessage message = sentTranscriptMessage.getMessage();
1029 handleSignalServiceDataMessage(message);
1030 }
1031 if (syncMessage.getBlockedList().isPresent()) {
1032 System.out.println("Received sync message with block list");
1033 System.out.println("Blocked numbers:");
1034 final BlockedListMessage blockedList = syncMessage.getBlockedList().get();
1035 for (String number : blockedList.getNumbers()) {
1036 System.out.println(" - " + number);
1037 }
1038 }
1039 if (syncMessage.getVerified().isPresent()) {
1040 System.out.println("Received sync message with verified identities:");
1041 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1042 System.out.println(" - " + verifiedMessage.getDestination() + ": " + verifiedMessage.getVerified());
1043 String safetyNumber = Util.formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(), verifiedMessage.getIdentityKey()));
1044 System.out.println(" " + safetyNumber);
1045 }
1046 if (syncMessage.getConfiguration().isPresent()) {
1047 System.out.println("Received sync message with configuration:");
1048 final ConfigurationMessage configurationMessage = syncMessage.getConfiguration().get();
1049 if (configurationMessage.getReadReceipts().isPresent()) {
1050 System.out.println(" - Read receipts: " + (configurationMessage.getReadReceipts().get() ? "enabled" : "disabled"));
1051 }
1052 }
1053 }
1054 if (content.getCallMessage().isPresent()) {
1055 System.out.println("Received a call message");
1056 SignalServiceCallMessage callMessage = content.getCallMessage().get();
1057 if (callMessage.getAnswerMessage().isPresent()) {
1058 AnswerMessage answerMessage = callMessage.getAnswerMessage().get();
1059 System.out.println("Answer message: " + answerMessage.getId() + ": " + answerMessage.getDescription());
1060 }
1061 if (callMessage.getBusyMessage().isPresent()) {
1062 BusyMessage busyMessage = callMessage.getBusyMessage().get();
1063 System.out.println("Busy message: " + busyMessage.getId());
1064 }
1065 if (callMessage.getHangupMessage().isPresent()) {
1066 HangupMessage hangupMessage = callMessage.getHangupMessage().get();
1067 System.out.println("Hangup message: " + hangupMessage.getId());
1068 }
1069 if (callMessage.getIceUpdateMessages().isPresent()) {
1070 List<IceUpdateMessage> iceUpdateMessages = callMessage.getIceUpdateMessages().get();
1071 for (IceUpdateMessage iceUpdateMessage : iceUpdateMessages) {
1072 System.out.println("Ice update message: " + iceUpdateMessage.getId() + ", sdp: " + iceUpdateMessage.getSdp());
1073 }
1074 }
1075 if (callMessage.getOfferMessage().isPresent()) {
1076 OfferMessage offerMessage = callMessage.getOfferMessage().get();
1077 System.out.println("Offer message: " + offerMessage.getId() + ": " + offerMessage.getDescription());
1078 }
1079 }
1080 if (content.getReceiptMessage().isPresent()) {
1081 System.out.println("Received a receipt message");
1082 SignalServiceReceiptMessage receiptMessage = content.getReceiptMessage().get();
1083 System.out.println(" - When: " + DateUtils.formatTimestamp(receiptMessage.getWhen()));
1084 if (receiptMessage.isDeliveryReceipt()) {
1085 System.out.println(" - Is delivery receipt");
1086 }
1087 if (receiptMessage.isReadReceipt()) {
1088 System.out.println(" - Is read receipt");
1089 }
1090 System.out.println(" - Timestamps:");
1091 for (long timestamp : receiptMessage.getTimestamps()) {
1092 System.out.println(" " + DateUtils.formatTimestamp(timestamp));
1093 }
1094 }
1095 if (content.getTypingMessage().isPresent()) {
1096 System.out.println("Received a typing message");
1097 SignalServiceTypingMessage typingMessage = content.getTypingMessage().get();
1098 System.out.println(" - Action: " + typingMessage.getAction());
1099 System.out.println(" - Timestamp: " + DateUtils.formatTimestamp(typingMessage.getTimestamp()));
1100 if (typingMessage.getGroupId().isPresent()) {
1101 GroupInfo group = m.getGroup(typingMessage.getGroupId().get());
1102 if (group != null) {
1103 System.out.println(" Name: " + group.name);
1104 } else {
1105 System.out.println(" Name: <Unknown group>");
1106 }
1107 }
1108 }
1109 }
1110 } else {
1111 System.out.println("Unknown message received.");
1112 }
1113 System.out.println();
1114 }
1115
1116 private void handleSignalServiceDataMessage(SignalServiceDataMessage message) {
1117 System.out.println("Message timestamp: " + DateUtils.formatTimestamp(message.getTimestamp()));
1118
1119 if (message.getBody().isPresent()) {
1120 System.out.println("Body: " + message.getBody().get());
1121 }
1122 if (message.getGroupInfo().isPresent()) {
1123 SignalServiceGroup groupInfo = message.getGroupInfo().get();
1124 System.out.println("Group info:");
1125 System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId()));
1126 if (groupInfo.getType() == SignalServiceGroup.Type.UPDATE && groupInfo.getName().isPresent()) {
1127 System.out.println(" Name: " + groupInfo.getName().get());
1128 } else {
1129 GroupInfo group = m.getGroup(groupInfo.getGroupId());
1130 if (group != null) {
1131 System.out.println(" Name: " + group.name);
1132 } else {
1133 System.out.println(" Name: <Unknown group>");
1134 }
1135 }
1136 System.out.println(" Type: " + groupInfo.getType());
1137 if (groupInfo.getMembers().isPresent()) {
1138 for (String member : groupInfo.getMembers().get()) {
1139 System.out.println(" Member: " + member);
1140 }
1141 }
1142 if (groupInfo.getAvatar().isPresent()) {
1143 System.out.println(" Avatar:");
1144 printAttachment(groupInfo.getAvatar().get());
1145 }
1146 }
1147 if (message.isEndSession()) {
1148 System.out.println("Is end session");
1149 }
1150 if (message.isExpirationUpdate()) {
1151 System.out.println("Is Expiration update: " + message.isExpirationUpdate());
1152 }
1153 if (message.getExpiresInSeconds() > 0) {
1154 System.out.println("Expires in: " + message.getExpiresInSeconds() + " seconds");
1155 }
1156 if (message.getProfileKey().isPresent()) {
1157 System.out.println("Profile key update, key length:" + message.getProfileKey().get().length);
1158 }
1159
1160 if (message.getQuote().isPresent()) {
1161 SignalServiceDataMessage.Quote quote = message.getQuote().get();
1162 System.out.println("Quote: (" + quote.getId() + ")");
1163 System.out.println(" Author: " + quote.getAuthor().getNumber());
1164 System.out.println(" Text: " + quote.getText());
1165 if (quote.getAttachments().size() > 0) {
1166 System.out.println(" Attachments: ");
1167 for (SignalServiceDataMessage.Quote.QuotedAttachment attachment : quote.getAttachments()) {
1168 System.out.println(" Filename: " + attachment.getFileName());
1169 System.out.println(" Type: " + attachment.getContentType());
1170 System.out.println(" Thumbnail:");
1171 if (attachment.getThumbnail() != null) {
1172 printAttachment(attachment.getThumbnail());
1173 }
1174 }
1175 }
1176 }
1177
1178 if (message.getAttachments().isPresent()) {
1179 System.out.println("Attachments: ");
1180 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1181 printAttachment(attachment);
1182 }
1183 }
1184 }
1185
1186 private void printAttachment(SignalServiceAttachment attachment) {
1187 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
1188 if (attachment.isPointer()) {
1189 final SignalServiceAttachmentPointer pointer = attachment.asPointer();
1190 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length);
1191 System.out.println(" Filename: " + (pointer.getFileName().isPresent() ? pointer.getFileName().get() : "-"));
1192 System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
1193 System.out.println(" Voice note: " + (pointer.getVoiceNote() ? "yes" : "no"));
1194 System.out.println(" Dimensions: " + pointer.getWidth() + "x" + pointer.getHeight());
1195 File file = m.getAttachmentFile(pointer.getId());
1196 if (file.exists()) {
1197 System.out.println(" Stored plaintext in: " + file);
1198 }
1199 }
1200 }
1201 }
1202
1203 private static class DbusReceiveMessageHandler extends ReceiveMessageHandler {
1204
1205 final DBusConnection conn;
1206
1207 DbusReceiveMessageHandler(Manager m, DBusConnection conn) {
1208 super(m);
1209 this.conn = conn;
1210 }
1211
1212 @Override
1213 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1214 super.handleMessage(envelope, content, exception);
1215
1216 JsonDbusReceiveMessageHandler.sendReceivedMessageToDbus(envelope, content, conn, m);
1217 }
1218 }
1219
1220 private static class JsonReceiveMessageHandler implements Manager.ReceiveMessageHandler {
1221
1222 final Manager m;
1223 final ObjectMapper jsonProcessor;
1224
1225 JsonReceiveMessageHandler(Manager m) {
1226 this.m = m;
1227 this.jsonProcessor = new ObjectMapper();
1228 jsonProcessor.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // disable autodetect
1229 jsonProcessor.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
1230 jsonProcessor.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
1231 jsonProcessor.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
1232 }
1233
1234 @Override
1235 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1236 ObjectNode result = jsonProcessor.createObjectNode();
1237 if (exception != null) {
1238 result.putPOJO("error", new JsonError(exception));
1239 }
1240 if (envelope != null) {
1241 result.putPOJO("envelope", new JsonMessageEnvelope(envelope, content));
1242 }
1243 try {
1244 jsonProcessor.writeValue(System.out, result);
1245 System.out.println();
1246 } catch (IOException e) {
1247 e.printStackTrace();
1248 }
1249 }
1250 }
1251
1252 private static class JsonDbusReceiveMessageHandler extends JsonReceiveMessageHandler {
1253
1254 final DBusConnection conn;
1255
1256 JsonDbusReceiveMessageHandler(Manager m, DBusConnection conn) {
1257 super(m);
1258 this.conn = conn;
1259 }
1260
1261 private static void sendReceivedMessageToDbus(SignalServiceEnvelope envelope, SignalServiceContent content, DBusConnection conn, Manager m) {
1262 if (envelope.isReceipt()) {
1263 try {
1264 conn.sendSignal(new Signal.ReceiptReceived(
1265 SIGNAL_OBJECTPATH,
1266 envelope.getTimestamp(),
1267 envelope.getSource()
1268 ));
1269 } catch (DBusException e) {
1270 e.printStackTrace();
1271 }
1272 } else if (content != null && content.getDataMessage().isPresent()) {
1273 SignalServiceDataMessage message = content.getDataMessage().get();
1274
1275 if (!message.isEndSession() &&
1276 !(message.getGroupInfo().isPresent() &&
1277 message.getGroupInfo().get().getType() != SignalServiceGroup.Type.DELIVER)) {
1278 List<String> attachments = new ArrayList<>();
1279 if (message.getAttachments().isPresent()) {
1280 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1281 if (attachment.isPointer()) {
1282 attachments.add(m.getAttachmentFile(attachment.asPointer().getId()).getAbsolutePath());
1283 }
1284 }
1285 }
1286
1287 try {
1288 conn.sendSignal(new Signal.MessageReceived(
1289 SIGNAL_OBJECTPATH,
1290 message.getTimestamp(),
1291 envelope.getSource(),
1292 message.getGroupInfo().isPresent() ? message.getGroupInfo().get().getGroupId() : new byte[0],
1293 message.getBody().isPresent() ? message.getBody().get() : "",
1294 attachments));
1295 } catch (DBusException e) {
1296 e.printStackTrace();
1297 }
1298 }
1299 }
1300 }
1301
1302 @Override
1303 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1304 super.handleMessage(envelope, content, exception);
1305
1306 sendReceivedMessageToDbus(envelope, content, conn, m);
1307 }
1308 }
1309 }