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