]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/Main.java
Update signal-service-java dependency
[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.Hex;
35 import org.freedesktop.dbus.DBusConnection;
36 import org.freedesktop.dbus.DBusSigHandler;
37 import org.freedesktop.dbus.exceptions.DBusException;
38 import org.freedesktop.dbus.exceptions.DBusExecutionException;
39 import org.whispersystems.libsignal.InvalidKeyException;
40 import org.whispersystems.libsignal.util.guava.Optional;
41 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
42 import org.whispersystems.signalservice.api.messages.*;
43 import org.whispersystems.signalservice.api.messages.calls.*;
44 import org.whispersystems.signalservice.api.messages.multidevice.*;
45 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
46 import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions;
47 import org.whispersystems.signalservice.api.push.exceptions.NetworkFailureException;
48 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
49 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
50 import org.whispersystems.signalservice.internal.push.LockedException;
51 import org.whispersystems.signalservice.internal.util.Base64;
52
53 import java.io.File;
54 import java.io.IOException;
55 import java.io.InputStream;
56 import java.io.StringWriter;
57 import java.net.URI;
58 import java.net.URISyntaxException;
59 import java.nio.charset.Charset;
60 import java.security.Security;
61 import java.text.DateFormat;
62 import java.text.SimpleDateFormat;
63 import java.util.*;
64 import java.util.concurrent.TimeUnit;
65 import java.util.concurrent.TimeoutException;
66
67 public class Main {
68
69 public static final String SIGNAL_BUSNAME = "org.asamk.Signal";
70 public static final String SIGNAL_OBJECTPATH = "/org/asamk/Signal";
71
72 private static final TimeZone tzUTC = TimeZone.getTimeZone("UTC");
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: " + formatTimestamp(d.getCreated()));
321 System.out.println(" Last seen: " + 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 = readAll(System.in);
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(), 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(), 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 = 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 String formatSafetyNumber(String digits) {
727 final int partCount = 12;
728 int partSize = digits.length() / partCount;
729 StringBuilder f = new StringBuilder(digits.length() + partCount);
730 for (int i = 0; i < partCount; i++) {
731 f.append(digits.substring(i * partSize, (i * partSize) + partSize)).append(" ");
732 }
733 return f.toString();
734 }
735
736 private static void handleGroupNotFoundException(GroupNotFoundException e) {
737 System.err.println("Failed to send to group: " + e.getMessage());
738 System.err.println("Aborting sending.");
739 }
740
741 private static void handleNotAGroupMemberException(NotAGroupMemberException e) {
742 System.err.println("Failed to send to group: " + e.getMessage());
743 System.err.println("Update the group on another device to readd the user to this group.");
744 System.err.println("Aborting sending.");
745 }
746
747
748 private static void handleDBusExecutionException(DBusExecutionException e) {
749 System.err.println("Cannot connect to dbus: " + e.getMessage());
750 System.err.println("Aborting.");
751 }
752
753 private static byte[] decodeGroupId(String groupId) {
754 try {
755 return Base64.decode(groupId);
756 } catch (IOException e) {
757 System.err.println("Failed to decode groupId (must be base64) \"" + groupId + "\": " + e.getMessage());
758 System.err.println("Aborting sending.");
759 System.exit(1);
760 return null;
761 }
762 }
763
764 private static Namespace parseArgs(String[] args) {
765 ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
766 .build()
767 .defaultHelp(true)
768 .description("Commandline interface for Signal.")
769 .version(Manager.PROJECT_NAME + " " + Manager.PROJECT_VERSION);
770
771 parser.addArgument("-v", "--version")
772 .help("Show package version.")
773 .action(Arguments.version());
774 parser.addArgument("--config")
775 .help("Set the path, where to store the config (Default: $HOME/.config/signal).");
776
777 MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
778 mut.addArgument("-u", "--username")
779 .help("Specify your phone number, that will be used for verification.");
780 mut.addArgument("--dbus")
781 .help("Make request via user dbus.")
782 .action(Arguments.storeTrue());
783 mut.addArgument("--dbus-system")
784 .help("Make request via system dbus.")
785 .action(Arguments.storeTrue());
786
787 Subparsers subparsers = parser.addSubparsers()
788 .title("subcommands")
789 .dest("command")
790 .description("valid subcommands")
791 .help("additional help");
792
793 Subparser parserLink = subparsers.addParser("link");
794 parserLink.addArgument("-n", "--name")
795 .help("Specify a name to describe this new device.");
796
797 Subparser parserAddDevice = subparsers.addParser("addDevice");
798 parserAddDevice.addArgument("--uri")
799 .required(true)
800 .help("Specify the uri contained in the QR code shown by the new device.");
801
802 Subparser parserDevices = subparsers.addParser("listDevices");
803
804 Subparser parserRemoveDevice = subparsers.addParser("removeDevice");
805 parserRemoveDevice.addArgument("-d", "--deviceId")
806 .type(int.class)
807 .required(true)
808 .help("Specify the device you want to remove. Use listDevices to see the deviceIds.");
809
810 Subparser parserRegister = subparsers.addParser("register");
811 parserRegister.addArgument("-v", "--voice")
812 .help("The verification should be done over voice, not sms.")
813 .action(Arguments.storeTrue());
814
815 Subparser parserUnregister = subparsers.addParser("unregister");
816 parserUnregister.help("Unregister the current device from the signal server.");
817
818 Subparser parserUpdateAccount = subparsers.addParser("updateAccount");
819 parserUpdateAccount.help("Update the account attributes on the signal server.");
820
821 Subparser parserSetPin = subparsers.addParser("setPin");
822 parserSetPin.addArgument("registrationLockPin")
823 .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)");
824
825 Subparser parserRemovePin = subparsers.addParser("removePin");
826
827 Subparser parserVerify = subparsers.addParser("verify");
828 parserVerify.addArgument("verificationCode")
829 .help("The verification code you received via sms or voice call.");
830 parserVerify.addArgument("-p", "--pin")
831 .help("The registration lock PIN, that was set by the user (Optional)");
832
833 Subparser parserSend = subparsers.addParser("send");
834 parserSend.addArgument("-g", "--group")
835 .help("Specify the recipient group ID.");
836 parserSend.addArgument("recipient")
837 .help("Specify the recipients' phone number.")
838 .nargs("*");
839 parserSend.addArgument("-m", "--message")
840 .help("Specify the message, if missing standard input is used.");
841 parserSend.addArgument("-a", "--attachment")
842 .nargs("*")
843 .help("Add file as attachment");
844 parserSend.addArgument("-e", "--endsession")
845 .help("Clear session state and send end session message.")
846 .action(Arguments.storeTrue());
847
848 Subparser parserLeaveGroup = subparsers.addParser("quitGroup");
849 parserLeaveGroup.addArgument("-g", "--group")
850 .required(true)
851 .help("Specify the recipient group ID.");
852
853 Subparser parserUpdateGroup = subparsers.addParser("updateGroup");
854 parserUpdateGroup.addArgument("-g", "--group")
855 .help("Specify the recipient group ID.");
856 parserUpdateGroup.addArgument("-n", "--name")
857 .help("Specify the new group name.");
858 parserUpdateGroup.addArgument("-a", "--avatar")
859 .help("Specify a new group avatar image file");
860 parserUpdateGroup.addArgument("-m", "--member")
861 .nargs("*")
862 .help("Specify one or more members to add to the group");
863
864 Subparser parserListGroups = subparsers.addParser("listGroups");
865 parserListGroups.addArgument("-d", "--detailed").action(Arguments.storeTrue())
866 .help("List members of each group");
867 parserListGroups.help("List group name and ids");
868
869 Subparser parserListIdentities = subparsers.addParser("listIdentities");
870 parserListIdentities.addArgument("-n", "--number")
871 .help("Only show identity keys for the given phone number.");
872
873 Subparser parserTrust = subparsers.addParser("trust");
874 parserTrust.addArgument("number")
875 .help("Specify the phone number, for which to set the trust.")
876 .required(true);
877 MutuallyExclusiveGroup mutTrust = parserTrust.addMutuallyExclusiveGroup();
878 mutTrust.addArgument("-a", "--trust-all-known-keys")
879 .help("Trust all known keys of this user, only use this for testing.")
880 .action(Arguments.storeTrue());
881 mutTrust.addArgument("-v", "--verified-fingerprint")
882 .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint.");
883
884 Subparser parserReceive = subparsers.addParser("receive");
885 parserReceive.addArgument("-t", "--timeout")
886 .type(double.class)
887 .help("Number of seconds to wait for new messages (negative values disable timeout)");
888 parserReceive.addArgument("--ignore-attachments")
889 .help("Don’t download attachments of received messages.")
890 .action(Arguments.storeTrue());
891 parserReceive.addArgument("--json")
892 .help("Output received messages in json format, one json object per line.")
893 .action(Arguments.storeTrue());
894
895 Subparser parserDaemon = subparsers.addParser("daemon");
896 parserDaemon.addArgument("--system")
897 .action(Arguments.storeTrue())
898 .help("Use DBus system bus instead of user bus.");
899 parserDaemon.addArgument("--ignore-attachments")
900 .help("Don’t download attachments of received messages.")
901 .action(Arguments.storeTrue());
902 parserDaemon.addArgument("--json")
903 .help("Output received messages in json format, one json object per line.")
904 .action(Arguments.storeTrue());
905
906 try {
907 Namespace ns = parser.parseArgs(args);
908 if ("link".equals(ns.getString("command"))) {
909 if (ns.getString("username") != null) {
910 parser.printUsage();
911 System.err.println("You cannot specify a username (phone number) when linking");
912 System.exit(2);
913 }
914 } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
915 if (ns.getString("username") == null) {
916 parser.printUsage();
917 System.err.println("You need to specify a username (phone number)");
918 System.exit(2);
919 }
920 if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"))) {
921 System.err.println("Invalid username (phone number), make sure you include the country code.");
922 System.exit(2);
923 }
924 }
925 if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
926 System.err.println("You cannot specify recipients by phone number and groups a the same time");
927 System.exit(2);
928 }
929 return ns;
930 } catch (ArgumentParserException e) {
931 parser.handleError(e);
932 return null;
933 }
934 }
935
936 private static void handleAssertionError(AssertionError e) {
937 System.err.println("Failed to send/receive message (Assertion): " + e.getMessage());
938 e.printStackTrace();
939 System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
940 }
941
942 private static void handleEncapsulatedExceptions(EncapsulatedExceptions e) {
943 System.err.println("Failed to send (some) messages:");
944 for (NetworkFailureException n : e.getNetworkExceptions()) {
945 System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
946 }
947 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
948 System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
949 }
950 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
951 System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
952 }
953 }
954
955 private static void handleIOException(IOException e) {
956 System.err.println("Failed to send message: " + e.getMessage());
957 }
958
959 private static String readAll(InputStream in) throws IOException {
960 StringWriter output = new StringWriter();
961 byte[] buffer = new byte[4096];
962 long count = 0;
963 int n;
964 while (-1 != (n = System.in.read(buffer))) {
965 output.write(new String(buffer, 0, n, Charset.defaultCharset()));
966 count += n;
967 }
968 return output.toString();
969 }
970
971 private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler {
972 final Manager m;
973
974 public ReceiveMessageHandler(Manager m) {
975 this.m = m;
976 }
977
978 @Override
979 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
980 SignalServiceAddress source = envelope.getSourceAddress();
981 ContactInfo sourceContact = m.getContact(source.getNumber());
982 System.out.println(String.format("Envelope from: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getNumber(), envelope.getSourceDevice()));
983 if (source.getRelay().isPresent()) {
984 System.out.println("Relayed by: " + source.getRelay().get());
985 }
986 System.out.println("Timestamp: " + formatTimestamp(envelope.getTimestamp()));
987 if (envelope.isUnidentifiedSender()) {
988 System.out.println("Sent by unidentified/sealed sender");
989 }
990
991 if (envelope.isReceipt()) {
992 System.out.println("Got receipt.");
993 } else if (envelope.isSignalMessage() | envelope.isPreKeySignalMessage()) {
994 if (exception != null) {
995 if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
996 org.whispersystems.libsignal.UntrustedIdentityException e = (org.whispersystems.libsignal.UntrustedIdentityException) exception;
997 System.out.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message.");
998 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");
999 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");
1000 } else {
1001 System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass().getSimpleName() + ")");
1002 }
1003 }
1004 if (content == null) {
1005 System.out.println("Failed to decrypt message.");
1006 } else {
1007 if (content.getDataMessage().isPresent()) {
1008 SignalServiceDataMessage message = content.getDataMessage().get();
1009 handleSignalServiceDataMessage(message);
1010 }
1011 if (content.getSyncMessage().isPresent()) {
1012 System.out.println("Received a sync message");
1013 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1014
1015 if (syncMessage.getContacts().isPresent()) {
1016 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
1017 if (contactsMessage.isComplete()) {
1018 System.out.println("Received complete sync contacts");
1019 } else {
1020 System.out.println("Received sync contacts");
1021 }
1022 printAttachment(contactsMessage.getContactsStream());
1023 }
1024 if (syncMessage.getGroups().isPresent()) {
1025 System.out.println("Received sync groups");
1026 printAttachment(syncMessage.getGroups().get());
1027 }
1028 if (syncMessage.getRead().isPresent()) {
1029 System.out.println("Received sync read messages list");
1030 for (ReadMessage rm : syncMessage.getRead().get()) {
1031 ContactInfo fromContact = m.getContact(rm.getSender());
1032 System.out.println("From: " + (fromContact == null ? "" : "“" + fromContact.name + "” ") + rm.getSender() + " Message timestamp: " + formatTimestamp(rm.getTimestamp()));
1033 }
1034 }
1035 if (syncMessage.getRequest().isPresent()) {
1036 System.out.println("Received sync request");
1037 if (syncMessage.getRequest().get().isContactsRequest()) {
1038 System.out.println(" - contacts request");
1039 }
1040 if (syncMessage.getRequest().get().isGroupsRequest()) {
1041 System.out.println(" - groups request");
1042 }
1043 }
1044 if (syncMessage.getSent().isPresent()) {
1045 System.out.println("Received sync sent message");
1046 final SentTranscriptMessage sentTranscriptMessage = syncMessage.getSent().get();
1047 String to;
1048 if (sentTranscriptMessage.getDestination().isPresent()) {
1049 String dest = sentTranscriptMessage.getDestination().get();
1050 ContactInfo destContact = m.getContact(dest);
1051 to = (destContact == null ? "" : "“" + destContact.name + "” ") + dest;
1052 } else {
1053 to = "Unknown";
1054 }
1055 System.out.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage.getTimestamp()));
1056 if (sentTranscriptMessage.getExpirationStartTimestamp() > 0) {
1057 System.out.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage.getExpirationStartTimestamp()));
1058 }
1059 SignalServiceDataMessage message = sentTranscriptMessage.getMessage();
1060 handleSignalServiceDataMessage(message);
1061 }
1062 if (syncMessage.getBlockedList().isPresent()) {
1063 System.out.println("Received sync message with block list");
1064 System.out.println("Blocked numbers:");
1065 final BlockedListMessage blockedList = syncMessage.getBlockedList().get();
1066 for (String number : blockedList.getNumbers()) {
1067 System.out.println(" - " + number);
1068 }
1069 }
1070 if (syncMessage.getVerified().isPresent()) {
1071 System.out.println("Received sync message with verified identities:");
1072 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1073 System.out.println(" - " + verifiedMessage.getDestination() + ": " + verifiedMessage.getVerified());
1074 String safetyNumber = formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(), verifiedMessage.getIdentityKey()));
1075 System.out.println(" " + safetyNumber);
1076 }
1077 if (syncMessage.getConfiguration().isPresent()) {
1078 System.out.println("Received sync message with configuration:");
1079 final ConfigurationMessage configurationMessage = syncMessage.getConfiguration().get();
1080 if (configurationMessage.getReadReceipts().isPresent()) {
1081 System.out.println(" - Read receipts: " + (configurationMessage.getReadReceipts().get() ? "enabled" : "disabled"));
1082 }
1083 }
1084 }
1085 if (content.getCallMessage().isPresent()) {
1086 System.out.println("Received a call message");
1087 SignalServiceCallMessage callMessage = content.getCallMessage().get();
1088 if (callMessage.getAnswerMessage().isPresent()) {
1089 AnswerMessage answerMessage = callMessage.getAnswerMessage().get();
1090 System.out.println("Answer message: " + answerMessage.getId() + ": " + answerMessage.getDescription());
1091 }
1092 if (callMessage.getBusyMessage().isPresent()) {
1093 BusyMessage busyMessage = callMessage.getBusyMessage().get();
1094 System.out.println("Busy message: " + busyMessage.getId());
1095 }
1096 if (callMessage.getHangupMessage().isPresent()) {
1097 HangupMessage hangupMessage = callMessage.getHangupMessage().get();
1098 System.out.println("Hangup message: " + hangupMessage.getId());
1099 }
1100 if (callMessage.getIceUpdateMessages().isPresent()) {
1101 List<IceUpdateMessage> iceUpdateMessages = callMessage.getIceUpdateMessages().get();
1102 for (IceUpdateMessage iceUpdateMessage : iceUpdateMessages) {
1103 System.out.println("Ice update message: " + iceUpdateMessage.getId() + ", sdp: " + iceUpdateMessage.getSdp());
1104 }
1105 }
1106 if (callMessage.getOfferMessage().isPresent()) {
1107 OfferMessage offerMessage = callMessage.getOfferMessage().get();
1108 System.out.println("Offer message: " + offerMessage.getId() + ": " + offerMessage.getDescription());
1109 }
1110 }
1111 if (content.getReceiptMessage().isPresent()) {
1112 System.out.println("Received a receipt message");
1113 SignalServiceReceiptMessage receiptMessage = content.getReceiptMessage().get();
1114 System.out.println(" - When: " + formatTimestamp(receiptMessage.getWhen()));
1115 if (receiptMessage.isDeliveryReceipt()) {
1116 System.out.println(" - Is delivery receipt");
1117 }
1118 if (receiptMessage.isReadReceipt()) {
1119 System.out.println(" - Is read receipt");
1120 }
1121 System.out.println(" - Timestamps:");
1122 for (long timestamp : receiptMessage.getTimestamps()) {
1123 System.out.println(" " + formatTimestamp(timestamp));
1124 }
1125 }
1126 if (content.getTypingMessage().isPresent()) {
1127 System.out.println("Received a typing message");
1128 SignalServiceTypingMessage typingMessage = content.getTypingMessage().get();
1129 System.out.println(" - Action: " + typingMessage.getAction());
1130 System.out.println(" - Timestamp: " + formatTimestamp(typingMessage.getTimestamp()));
1131 if (typingMessage.getGroupId().isPresent()) {
1132 GroupInfo group = m.getGroup(typingMessage.getGroupId().get());
1133 if (group != null) {
1134 System.out.println(" Name: " + group.name);
1135 } else {
1136 System.out.println(" Name: <Unknown group>");
1137 }
1138 }
1139 }
1140 }
1141 } else {
1142 System.out.println("Unknown message received.");
1143 }
1144 System.out.println();
1145 }
1146
1147 private void handleSignalServiceDataMessage(SignalServiceDataMessage message) {
1148 System.out.println("Message timestamp: " + formatTimestamp(message.getTimestamp()));
1149
1150 if (message.getBody().isPresent()) {
1151 System.out.println("Body: " + message.getBody().get());
1152 }
1153 if (message.getGroupInfo().isPresent()) {
1154 SignalServiceGroup groupInfo = message.getGroupInfo().get();
1155 System.out.println("Group info:");
1156 System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId()));
1157 if (groupInfo.getType() == SignalServiceGroup.Type.UPDATE && groupInfo.getName().isPresent()) {
1158 System.out.println(" Name: " + groupInfo.getName().get());
1159 } else {
1160 GroupInfo group = m.getGroup(groupInfo.getGroupId());
1161 if (group != null) {
1162 System.out.println(" Name: " + group.name);
1163 } else {
1164 System.out.println(" Name: <Unknown group>");
1165 }
1166 }
1167 System.out.println(" Type: " + groupInfo.getType());
1168 if (groupInfo.getMembers().isPresent()) {
1169 for (String member : groupInfo.getMembers().get()) {
1170 System.out.println(" Member: " + member);
1171 }
1172 }
1173 if (groupInfo.getAvatar().isPresent()) {
1174 System.out.println(" Avatar:");
1175 printAttachment(groupInfo.getAvatar().get());
1176 }
1177 }
1178 if (message.isEndSession()) {
1179 System.out.println("Is end session");
1180 }
1181 if (message.isExpirationUpdate()) {
1182 System.out.println("Is Expiration update: " + message.isExpirationUpdate());
1183 }
1184 if (message.getExpiresInSeconds() > 0) {
1185 System.out.println("Expires in: " + message.getExpiresInSeconds() + " seconds");
1186 }
1187 if (message.getProfileKey().isPresent()) {
1188 System.out.println("Profile key update, key length:" + message.getProfileKey().get().length);
1189 }
1190
1191 if (message.getQuote().isPresent()) {
1192 SignalServiceDataMessage.Quote quote = message.getQuote().get();
1193 System.out.println("Quote: (" + quote.getId() + ")");
1194 System.out.println(" Author: " + quote.getAuthor().getNumber());
1195 System.out.println(" Text: " + quote.getText());
1196 if (quote.getAttachments().size() > 0) {
1197 System.out.println(" Attachments: ");
1198 for (SignalServiceDataMessage.Quote.QuotedAttachment attachment : quote.getAttachments()) {
1199 System.out.println(" Filename: " + attachment.getFileName());
1200 System.out.println(" Type: " + attachment.getContentType());
1201 System.out.println(" Thumbnail:");
1202 if (attachment.getThumbnail() != null) {
1203 printAttachment(attachment.getThumbnail());
1204 }
1205 }
1206 }
1207 }
1208
1209 if (message.getAttachments().isPresent()) {
1210 System.out.println("Attachments: ");
1211 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1212 printAttachment(attachment);
1213 }
1214 }
1215 }
1216
1217 private void printAttachment(SignalServiceAttachment attachment) {
1218 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
1219 if (attachment.isPointer()) {
1220 final SignalServiceAttachmentPointer pointer = attachment.asPointer();
1221 System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length);
1222 System.out.println(" Filename: " + (pointer.getFileName().isPresent() ? pointer.getFileName().get() : "-"));
1223 System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "<unavailable>") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : ""));
1224 System.out.println(" Voice note: " + (pointer.getVoiceNote() ? "yes" : "no"));
1225 System.out.println(" Dimensions: " + pointer.getWidth() + "x" + pointer.getHeight());
1226 File file = m.getAttachmentFile(pointer.getId());
1227 if (file.exists()) {
1228 System.out.println(" Stored plaintext in: " + file);
1229 }
1230 }
1231 }
1232 }
1233
1234 private static class DbusReceiveMessageHandler extends ReceiveMessageHandler {
1235 final DBusConnection conn;
1236
1237 public DbusReceiveMessageHandler(Manager m, DBusConnection conn) {
1238 super(m);
1239 this.conn = conn;
1240 }
1241
1242 @Override
1243 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1244 super.handleMessage(envelope, content, exception);
1245
1246 JsonDbusReceiveMessageHandler.sendReceivedMessageToDbus(envelope, content, conn, m);
1247 }
1248 }
1249
1250 private static class JsonReceiveMessageHandler implements Manager.ReceiveMessageHandler {
1251 final Manager m;
1252 final ObjectMapper jsonProcessor;
1253
1254 public JsonReceiveMessageHandler(Manager m) {
1255 this.m = m;
1256 this.jsonProcessor = new ObjectMapper();
1257 jsonProcessor.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // disable autodetect
1258 jsonProcessor.enable(SerializationFeature.WRITE_NULL_MAP_VALUES);
1259 jsonProcessor.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
1260 jsonProcessor.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
1261 }
1262
1263 @Override
1264 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1265 ObjectNode result = jsonProcessor.createObjectNode();
1266 if (exception != null) {
1267 result.putPOJO("error", new JsonError(exception));
1268 }
1269 if (envelope != null) {
1270 result.putPOJO("envelope", new JsonMessageEnvelope(envelope, content));
1271 }
1272 try {
1273 jsonProcessor.writeValue(System.out, result);
1274 System.out.println();
1275 } catch (IOException e) {
1276 e.printStackTrace();
1277 }
1278 }
1279 }
1280
1281 private static class JsonDbusReceiveMessageHandler extends JsonReceiveMessageHandler {
1282 final DBusConnection conn;
1283
1284 public JsonDbusReceiveMessageHandler(Manager m, DBusConnection conn) {
1285 super(m);
1286 this.conn = conn;
1287 }
1288
1289 @Override
1290 public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
1291 super.handleMessage(envelope, content, exception);
1292
1293 sendReceivedMessageToDbus(envelope, content, conn, m);
1294 }
1295
1296 private static void sendReceivedMessageToDbus(SignalServiceEnvelope envelope, SignalServiceContent content, DBusConnection conn, Manager m) {
1297 if (envelope.isReceipt()) {
1298 try {
1299 conn.sendSignal(new Signal.ReceiptReceived(
1300 SIGNAL_OBJECTPATH,
1301 envelope.getTimestamp(),
1302 envelope.getSource()
1303 ));
1304 } catch (DBusException e) {
1305 e.printStackTrace();
1306 }
1307 } else if (content != null && content.getDataMessage().isPresent()) {
1308 SignalServiceDataMessage message = content.getDataMessage().get();
1309
1310 if (!message.isEndSession() &&
1311 !(message.getGroupInfo().isPresent() &&
1312 message.getGroupInfo().get().getType() != SignalServiceGroup.Type.DELIVER)) {
1313 List<String> attachments = new ArrayList<>();
1314 if (message.getAttachments().isPresent()) {
1315 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1316 if (attachment.isPointer()) {
1317 attachments.add(m.getAttachmentFile(attachment.asPointer().getId()).getAbsolutePath());
1318 }
1319 }
1320 }
1321
1322 try {
1323 conn.sendSignal(new Signal.MessageReceived(
1324 SIGNAL_OBJECTPATH,
1325 message.getTimestamp(),
1326 envelope.getSource(),
1327 message.getGroupInfo().isPresent() ? message.getGroupInfo().get().getGroupId() : new byte[0],
1328 message.getBody().isPresent() ? message.getBody().get() : "",
1329 attachments));
1330 } catch (DBusException e) {
1331 e.printStackTrace();
1332 }
1333 }
1334 }
1335 }
1336 }
1337
1338 private static String formatTimestamp(long timestamp) {
1339 Date date = new Date(timestamp);
1340 final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
1341 df.setTimeZone(tzUTC);
1342 return timestamp + " (" + df.format(date) + ")";
1343 }
1344 }