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