2 Copyright (C) 2015-2020 AsamK and contributors
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.
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.
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/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.Signal
;
20 import org
.asamk
.signal
.AttachmentInvalidException
;
21 import org
.asamk
.signal
.GroupNotFoundException
;
22 import org
.asamk
.signal
.NotAGroupMemberException
;
23 import org
.asamk
.signal
.TrustLevel
;
24 import org
.asamk
.signal
.UserAlreadyExists
;
25 import org
.asamk
.signal
.storage
.SignalAccount
;
26 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
27 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
28 import org
.asamk
.signal
.storage
.groups
.JsonGroupStore
;
29 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
30 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
31 import org
.asamk
.signal
.util
.IOUtils
;
32 import org
.asamk
.signal
.util
.Util
;
33 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
34 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
35 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
36 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
37 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
38 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
39 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
40 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
41 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
42 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
43 import org
.signal
.libsignal
.metadata
.SelfSendException
;
44 import org
.whispersystems
.libsignal
.IdentityKey
;
45 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
46 import org
.whispersystems
.libsignal
.InvalidKeyException
;
47 import org
.whispersystems
.libsignal
.InvalidMessageException
;
48 import org
.whispersystems
.libsignal
.InvalidVersionException
;
49 import org
.whispersystems
.libsignal
.ecc
.Curve
;
50 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
51 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
52 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
53 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
54 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
55 import org
.whispersystems
.libsignal
.util
.Medium
;
56 import org
.whispersystems
.libsignal
.util
.Pair
;
57 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
58 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
59 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
60 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
61 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
62 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
63 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
64 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
65 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
66 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
70 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
71 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
72 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
73 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
74 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
75 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
76 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
77 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
78 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
79 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
80 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
81 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
82 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
83 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
84 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
85 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
86 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
87 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
88 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
89 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
90 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
91 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
92 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
93 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
94 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
95 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
96 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
97 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
98 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
99 import org
.whispersystems
.util
.Base64
;
102 import java
.io
.FileInputStream
;
103 import java
.io
.FileNotFoundException
;
104 import java
.io
.FileOutputStream
;
105 import java
.io
.IOException
;
106 import java
.io
.InputStream
;
107 import java
.io
.OutputStream
;
109 import java
.nio
.file
.Files
;
110 import java
.nio
.file
.Paths
;
111 import java
.nio
.file
.StandardCopyOption
;
112 import java
.util
.ArrayList
;
113 import java
.util
.Arrays
;
114 import java
.util
.Collection
;
115 import java
.util
.Collections
;
116 import java
.util
.Date
;
117 import java
.util
.HashSet
;
118 import java
.util
.LinkedList
;
119 import java
.util
.List
;
120 import java
.util
.Locale
;
121 import java
.util
.Map
;
122 import java
.util
.Objects
;
123 import java
.util
.Set
;
124 import java
.util
.concurrent
.TimeUnit
;
125 import java
.util
.concurrent
.TimeoutException
;
127 public class Manager
implements Signal
{
129 private final String settingsPath
;
130 private final String dataPath
;
131 private final String attachmentsPath
;
132 private final String avatarsPath
;
133 private final SleepTimer timer
= new UptimeSleepTimer();
135 private SignalAccount account
;
136 private String username
;
137 private SignalServiceAccountManager accountManager
;
138 private SignalServiceMessagePipe messagePipe
= null;
139 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
141 public Manager(String username
, String settingsPath
) {
142 this.username
= username
;
143 this.settingsPath
= settingsPath
;
144 this.dataPath
= this.settingsPath
+ "/data";
145 this.attachmentsPath
= this.settingsPath
+ "/attachments";
146 this.avatarsPath
= this.settingsPath
+ "/avatars";
150 public String
getUsername() {
154 private SignalServiceAddress
getSelfAddress() {
155 return new SignalServiceAddress(null, username
);
158 private SignalServiceAccountManager
getSignalServiceAccountManager() {
159 return new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, null, account
.getUsername(), account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
162 private IdentityKey
getIdentity() {
163 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
166 public int getDeviceId() {
167 return account
.getDeviceId();
170 private String
getMessageCachePath() {
171 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
174 private String
getMessageCachePath(String sender
) {
175 return getMessageCachePath() + "/" + sender
.replace("/", "_");
178 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
179 String cachePath
= getMessageCachePath(sender
);
180 IOUtils
.createPrivateDirectories(cachePath
);
181 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
184 public boolean userHasKeys() {
185 return account
!= null && account
.getSignalProtocolStore() != null;
188 public void init() throws IOException
{
189 if (!SignalAccount
.userExists(dataPath
, username
)) {
192 account
= SignalAccount
.load(dataPath
, username
);
194 migrateLegacyConfigs();
196 accountManager
= getSignalServiceAccountManager();
198 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
202 } catch (AuthorizationFailedException e
) {
203 System
.err
.println("Authorization failed, was the number registered elsewhere?");
208 private void migrateLegacyConfigs() {
209 // Copy group avatars that were previously stored in the attachments folder
210 // to the new avatar folder
211 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
212 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
213 File avatarFile
= getGroupAvatarFile(g
.groupId
);
214 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
215 if (!avatarFile
.exists() && attachmentFile
.exists()) {
217 IOUtils
.createPrivateDirectories(avatarsPath
);
218 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
219 } catch (Exception e
) {
224 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
227 if (account
.getProfileKey() == null) {
228 // Old config file, creating new profile key
229 account
.setProfileKey(KeyUtils
.createProfileKey());
234 private void createNewIdentity() throws IOException
{
235 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
236 int registrationId
= KeyHelper
.generateRegistrationId(false);
237 if (username
== null) {
238 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
240 byte[] profileKey
= KeyUtils
.createProfileKey();
241 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
246 public boolean isRegistered() {
247 return account
!= null && account
.isRegistered();
250 public void register(boolean voiceVerification
) throws IOException
{
251 if (account
== null) {
254 account
.setPassword(KeyUtils
.createPassword());
255 accountManager
= getSignalServiceAccountManager();
257 if (voiceVerification
) {
258 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent(), Optional
.<String
>absent());
260 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent(), Optional
.<String
>absent());
263 account
.setRegistered(false);
267 public void updateAccountAttributes() throws IOException
{
268 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), account
.getRegistrationLock(), getSelfUnidentifiedAccessKey(), false);
271 public void setProfileName(String name
) throws IOException
{
272 accountManager
.setProfileName(account
.getProfileKey(), name
);
275 public void setProfileAvatar(File avatar
) throws IOException
{
276 final StreamDetails streamDetails
= Utils
.createStreamDetailsFromFile(avatar
);
277 accountManager
.setProfileAvatar(account
.getProfileKey(), streamDetails
);
278 streamDetails
.getStream().close();
281 public void removeProfileAvatar() throws IOException
{
282 accountManager
.setProfileAvatar(account
.getProfileKey(), null);
285 public void unregister() throws IOException
{
286 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
287 // If this is the master device, other users can't send messages to this number anymore.
288 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
289 accountManager
.setGcmId(Optional
.<String
>absent());
291 account
.setRegistered(false);
295 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
296 if (account
== null) {
299 account
.setPassword(KeyUtils
.createPassword());
300 accountManager
= getSignalServiceAccountManager();
301 String uuid
= accountManager
.getNewDeviceUuid();
303 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
306 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
307 account
.setSignalingKey(KeyUtils
.createSignalingKey());
308 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
310 username
= ret
.getNumber();
311 // TODO do this check before actually registering
312 if (SignalAccount
.userExists(dataPath
, username
)) {
313 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
316 // Create new account with the synced identity
317 byte[] profileKey
= ret
.getProfileKey();
318 if (profileKey
== null) {
319 profileKey
= KeyUtils
.createProfileKey();
321 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
326 requestSyncContacts();
327 requestSyncBlocked();
328 requestSyncConfiguration();
333 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
334 List
<DeviceInfo
> devices
= accountManager
.getDevices();
335 account
.setMultiDevice(devices
.size() > 1);
340 public void removeLinkedDevices(int deviceId
) throws IOException
{
341 accountManager
.removeDevice(deviceId
);
342 List
<DeviceInfo
> devices
= accountManager
.getDevices();
343 account
.setMultiDevice(devices
.size() > 1);
347 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
348 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
350 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
353 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
354 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
355 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
357 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
358 account
.setMultiDevice(true);
362 private List
<PreKeyRecord
> generatePreKeys() {
363 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
365 final int offset
= account
.getPreKeyIdOffset();
366 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
367 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
368 ECKeyPair keyPair
= Curve
.generateKeyPair();
369 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
374 account
.addPreKeys(records
);
380 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
382 ECKeyPair keyPair
= Curve
.generateKeyPair();
383 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
384 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
386 account
.addSignedPreKey(record);
390 } catch (InvalidKeyException e
) {
391 throw new AssertionError(e
);
395 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
396 verificationCode
= verificationCode
.replace("-", "");
397 account
.setSignalingKey(KeyUtils
.createSignalingKey());
398 // TODO make unrestricted unidentified access configurable
399 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, null, getSelfUnidentifiedAccessKey(), false);
401 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
402 account
.setRegistered(true);
403 account
.setRegistrationLockPin(pin
);
409 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
410 if (pin
.isPresent()) {
411 account
.setRegistrationLockPin(pin
.get());
412 throw new RuntimeException("Not implemented anymore, will be replaced with KBS");
414 account
.setRegistrationLockPin(null);
415 accountManager
.removeV1Pin();
420 private void refreshPreKeys() throws IOException
{
421 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
422 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
423 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
425 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
428 private SignalServiceMessageReceiver
getMessageReceiver() {
429 return new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
432 private SignalServiceMessageSender
getMessageSender() {
433 return new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(),
434 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
437 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
438 File file
= getGroupAvatarFile(groupId
);
439 if (!file
.exists()) {
440 return Optional
.absent();
443 return Optional
.of(Utils
.createAttachment(file
));
446 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
447 File file
= getContactAvatarFile(number
);
448 if (!file
.exists()) {
449 return Optional
.absent();
452 return Optional
.of(Utils
.createAttachment(file
));
455 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
456 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
458 throw new GroupNotFoundException(groupId
);
460 for (String member
: g
.members
) {
461 if (member
.equals(this.username
)) {
465 throw new NotAGroupMemberException(groupId
, g
.name
);
468 public List
<GroupInfo
> getGroups() {
469 return account
.getGroupStore().getGroups();
473 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
475 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
476 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
477 if (attachments
!= null) {
478 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
480 if (groupId
!= null) {
481 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
484 messageBuilder
.asGroupMessage(group
);
486 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
487 if (thread
!= null) {
488 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
491 final GroupInfo g
= getGroupForSending(groupId
);
493 // Don't send group message to ourself
494 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
495 membersSend
.remove(this.username
);
496 sendMessageLegacy(messageBuilder
, membersSend
);
499 public void sendGroupMessageReaction(String emoji
, boolean remove
, SignalServiceAddress targetAuthor
,
500 long targetSentTimestamp
, byte[] groupId
)
501 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
502 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
);
503 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
504 .withReaction(reaction
)
505 .withProfileKey(account
.getProfileKey());
506 if (groupId
!= null) {
507 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
510 messageBuilder
.asGroupMessage(group
);
512 final GroupInfo g
= getGroupForSending(groupId
);
513 // Don't send group message to ourself
514 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
515 membersSend
.remove(this.username
);
516 sendMessageLegacy(messageBuilder
, membersSend
);
519 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
520 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
524 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
525 .asGroupMessage(group
);
527 final GroupInfo g
= getGroupForSending(groupId
);
528 g
.members
.remove(this.username
);
529 account
.getGroupStore().updateGroup(g
);
531 sendMessageLegacy(messageBuilder
, g
.members
);
534 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
536 if (groupId
== null) {
538 g
= new GroupInfo(KeyUtils
.createGroupId());
539 g
.members
.add(username
);
541 g
= getGroupForSending(groupId
);
548 if (members
!= null) {
549 Set
<String
> newMembers
= new HashSet
<>();
550 for (String member
: members
) {
552 member
= Utils
.canonicalizeNumber(member
, username
);
553 } catch (InvalidNumberException e
) {
554 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
555 System
.err
.println("Aborting…");
558 if (g
.members
.contains(member
)) {
561 newMembers
.add(member
);
562 g
.members
.add(member
);
564 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
565 if (contacts
.size() != newMembers
.size()) {
566 // Some of the new members are not registered on Signal
567 for (ContactTokenDetails contact
: contacts
) {
568 newMembers
.remove(contact
.getNumber());
570 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
571 System
.err
.println("Aborting…");
576 if (avatarFile
!= null) {
577 IOUtils
.createPrivateDirectories(avatarsPath
);
578 File aFile
= getGroupAvatarFile(g
.groupId
);
579 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
582 account
.getGroupStore().updateGroup(g
);
584 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
586 // Don't send group message to ourself
587 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
588 membersSend
.remove(this.username
);
589 sendMessageLegacy(messageBuilder
, membersSend
);
593 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
594 if (groupId
== null) {
597 GroupInfo g
= getGroupForSending(groupId
);
599 if (!g
.members
.contains(recipient
)) {
603 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
605 // Send group message only to the recipient who requested it
606 final List
<String
> membersSend
= new ArrayList
<>();
607 membersSend
.add(recipient
);
608 sendMessageLegacy(messageBuilder
, membersSend
);
611 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
612 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
615 .withMembers(new ArrayList
<>(g
.getMembers()));
617 File aFile
= getGroupAvatarFile(g
.groupId
);
618 if (aFile
.exists()) {
620 group
.withAvatar(Utils
.createAttachment(aFile
));
621 } catch (IOException e
) {
622 throw new AttachmentInvalidException(aFile
.toString(), e
);
626 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
627 .asGroupMessage(group
.build());
629 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
630 if (thread
!= null) {
631 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
634 return messageBuilder
;
637 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
638 if (groupId
== null) {
642 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
645 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
646 .asGroupMessage(group
.build());
648 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
649 if (thread
!= null) {
650 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
653 // Send group info request message to the recipient who sent us a message with this groupId
654 final List
<String
> membersSend
= new ArrayList
<>();
655 membersSend
.add(recipient
);
656 sendMessageLegacy(messageBuilder
, membersSend
);
660 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
661 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
662 List
<String
> recipients
= new ArrayList
<>(1);
663 recipients
.add(recipient
);
664 sendMessage(message
, attachments
, recipients
);
668 public void sendMessage(String messageText
, List
<String
> attachments
,
669 List
<String
> recipients
)
670 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
671 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
672 if (attachments
!= null) {
673 List
<SignalServiceAttachment
> attachmentStreams
= Utils
.getSignalServiceAttachments(attachments
);
675 // Upload attachments here, so we only upload once even for multiple recipients
676 SignalServiceMessageSender messageSender
= getMessageSender();
677 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
678 for (SignalServiceAttachment attachment
: attachmentStreams
) {
679 if (attachment
.isStream()) {
680 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
681 } else if (attachment
.isPointer()) {
682 attachmentPointers
.add(attachment
.asPointer());
686 messageBuilder
.withAttachments(attachmentPointers
);
688 messageBuilder
.withProfileKey(account
.getProfileKey());
689 sendMessageLegacy(messageBuilder
, recipients
);
692 public void sendMessageReaction(String emoji
, boolean remove
, SignalServiceAddress targetAuthor
,
693 long targetSentTimestamp
, List
<String
> recipients
)
694 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
695 SignalServiceDataMessage
.Reaction reaction
= new SignalServiceDataMessage
.Reaction(emoji
, remove
, targetAuthor
, targetSentTimestamp
);
696 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
697 .withReaction(reaction
)
698 .withProfileKey(account
.getProfileKey());
699 sendMessageLegacy(messageBuilder
, recipients
);
703 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
704 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
705 .asEndSessionMessage();
707 sendMessageLegacy(messageBuilder
, recipients
);
711 public String
getContactName(String number
) throws InvalidNumberException
{
712 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
713 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
714 if (contact
== null) {
722 public void setContactName(String number
, String name
) throws InvalidNumberException
{
723 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
724 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
725 if (contact
== null) {
726 contact
= new ContactInfo();
727 contact
.number
= canonicalizedNumber
;
728 System
.err
.println("Add contact " + canonicalizedNumber
+ " named " + name
);
730 System
.err
.println("Updating contact " + canonicalizedNumber
+ " name " + contact
.name
+ " -> " + name
);
733 account
.getContactStore().updateContact(contact
);
738 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
739 number
= Utils
.canonicalizeNumber(number
, username
);
740 ContactInfo contact
= account
.getContactStore().getContact(number
);
741 if (contact
== null) {
742 contact
= new ContactInfo();
743 contact
.number
= number
;
744 System
.err
.println("Adding and " + (blocked ?
"blocking" : "unblocking") + " contact " + number
);
746 System
.err
.println((blocked ?
"Blocking" : "Unblocking") + " contact " + number
);
748 contact
.blocked
= blocked
;
749 account
.getContactStore().updateContact(contact
);
754 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) throws GroupNotFoundException
{
755 GroupInfo group
= getGroup(groupId
);
757 throw new GroupNotFoundException(groupId
);
759 System
.err
.println((blocked ?
"Blocking" : "Unblocking") + " group " + Base64
.encodeBytes(groupId
));
760 group
.blocked
= blocked
;
761 account
.getGroupStore().updateGroup(group
);
767 public List
<byte[]> getGroupIds() {
768 List
<GroupInfo
> groups
= getGroups();
769 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
770 for (GroupInfo group
: groups
) {
771 ids
.add(group
.groupId
);
777 public String
getGroupName(byte[] groupId
) {
778 GroupInfo group
= getGroup(groupId
);
787 public List
<String
> getGroupMembers(byte[] groupId
) {
788 GroupInfo group
= getGroup(groupId
);
790 return new ArrayList
<>();
792 return new ArrayList
<>(group
.members
);
797 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
798 if (groupId
.length
== 0) {
801 if (name
.isEmpty()) {
804 if (members
.size() == 0) {
807 if (avatar
.isEmpty()) {
810 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
814 * Change the expiration timer for a thread (number of groupId)
816 * @param numberOrGroupId
817 * @param messageExpirationTimer
819 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
820 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
821 thread
.messageExpirationTime
= messageExpirationTimer
;
822 account
.getThreadStore().updateThread(thread
);
825 private void requestSyncGroups() throws IOException
{
826 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
827 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
829 sendSyncMessage(message
);
830 } catch (UntrustedIdentityException e
) {
835 private void requestSyncContacts() throws IOException
{
836 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
837 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
839 sendSyncMessage(message
);
840 } catch (UntrustedIdentityException e
) {
845 private void requestSyncBlocked() throws IOException
{
846 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
847 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
849 sendSyncMessage(message
);
850 } catch (UntrustedIdentityException e
) {
855 private void requestSyncConfiguration() throws IOException
{
856 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
857 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
859 sendSyncMessage(message
);
860 } catch (UntrustedIdentityException e
) {
865 private byte[] getSelfUnidentifiedAccessKey() {
866 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
869 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
874 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
876 return Optional
.absent();
879 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
880 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
881 for (SignalServiceAddress recipient
: recipients
) {
882 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
887 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
889 return Optional
.absent();
892 private void sendSyncMessage(SignalServiceSyncMessage message
)
893 throws IOException
, UntrustedIdentityException
{
894 SignalServiceMessageSender messageSender
= getMessageSender();
896 messageSender
.sendMessage(message
, getAccessForSync());
897 } catch (UntrustedIdentityException e
) {
898 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
904 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
906 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
907 throws EncapsulatedExceptions
, IOException
{
908 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
910 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
911 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
912 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
914 for (SendMessageResult result
: results
) {
915 if (result
.isUnregisteredFailure()) {
916 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber().get(), null));
917 } else if (result
.isNetworkFailure()) {
918 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber().get(), null));
919 } else if (result
.getIdentityFailure() != null) {
920 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber().get(), result
.getIdentityFailure().getIdentityKey()));
923 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
924 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
928 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
930 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
931 if (recipientsTS
== null) {
933 return Collections
.emptyList();
936 SignalServiceDataMessage message
= null;
938 SignalServiceMessageSender messageSender
= getMessageSender();
940 message
= messageBuilder
.build();
941 if (message
.getGroupInfo().isPresent()) {
943 final boolean isRecipientUpdate
= false;
944 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
945 for (SendMessageResult r
: result
) {
946 if (r
.getIdentityFailure() != null) {
947 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber().get(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
951 } catch (UntrustedIdentityException e
) {
952 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
953 return Collections
.emptyList();
955 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(getSelfAddress())) {
956 SignalServiceAddress recipient
= getSelfAddress();
957 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
958 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
959 message
.getTimestamp(),
961 message
.getExpiresInSeconds(),
962 Collections
.singletonMap(recipient
, unidentifiedAccess
.isPresent()),
964 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
966 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
968 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
969 } catch (UntrustedIdentityException e
) {
970 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
971 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
975 // Send to all individually, so sync messages are sent correctly
976 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
977 for (SignalServiceAddress address
: recipientsTS
) {
978 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber().get());
979 if (thread
!= null) {
980 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
982 messageBuilder
.withExpiration(0);
984 message
= messageBuilder
.build();
986 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
988 } catch (UntrustedIdentityException e
) {
989 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
990 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
996 if (message
!= null && message
.isEndSession()) {
997 for (SignalServiceAddress recipient
: recipientsTS
) {
998 handleEndSession(recipient
.getNumber().get());
1005 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
1006 SignalServiceCipher cipher
= new SignalServiceCipher(getSelfAddress(), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
1008 return cipher
.decrypt(envelope
);
1009 } catch (ProtocolUntrustedIdentityException e
) {
1010 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
1011 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
1016 private void handleEndSession(String source
) {
1017 account
.getSignalProtocolStore().deleteAllSessions(source
);
1020 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, SignalServiceAddress destination
, boolean ignoreAttachments
) {
1022 if (message
.getGroupInfo().isPresent()) {
1023 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1024 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
1025 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
1026 switch (groupInfo
.getType()) {
1028 if (group
== null) {
1029 group
= new GroupInfo(groupInfo
.getGroupId());
1032 if (groupInfo
.getAvatar().isPresent()) {
1033 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1034 if (avatar
.isPointer()) {
1036 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
1037 } catch (IOException
| InvalidMessageException e
) {
1038 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
1043 if (groupInfo
.getName().isPresent()) {
1044 group
.name
= groupInfo
.getName().get();
1047 if (groupInfo
.getMembers().isPresent()) {
1048 group
.addMembers(groupInfo
.getMembers().get());
1051 account
.getGroupStore().updateGroup(group
);
1054 if (group
== null) {
1056 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1057 } catch (IOException
| EncapsulatedExceptions e
) {
1058 e
.printStackTrace();
1063 if (group
== null) {
1065 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1066 } catch (IOException
| EncapsulatedExceptions e
) {
1067 e
.printStackTrace();
1070 group
.members
.remove(source
);
1071 account
.getGroupStore().updateGroup(group
);
1075 if (group
!= null) {
1077 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1078 } catch (IOException
| EncapsulatedExceptions e
) {
1079 e
.printStackTrace();
1080 } catch (NotAGroupMemberException e
) {
1081 // We have left this group, so don't send a group update message
1088 threadId
= destination
.getNumber().get();
1093 if (message
.isEndSession()) {
1094 handleEndSession(isSync ? destination
.getNumber().get() : source
);
1096 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1097 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1098 if (thread
== null) {
1099 thread
= new ThreadInfo();
1100 thread
.id
= threadId
;
1102 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1103 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1104 account
.getThreadStore().updateThread(thread
);
1107 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1108 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1109 if (attachment
.isPointer()) {
1111 retrieveAttachment(attachment
.asPointer());
1112 } catch (IOException
| InvalidMessageException e
) {
1113 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1118 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1119 if (source
.equals(username
)) {
1120 this.account
.setProfileKey(message
.getProfileKey().get());
1122 ContactInfo contact
= account
.getContactStore().getContact(source
);
1123 if (contact
== null) {
1124 contact
= new ContactInfo();
1125 contact
.number
= source
;
1127 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1129 if (message
.getPreviews().isPresent()) {
1130 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1131 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1132 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1133 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1135 retrieveAttachment(attachment
);
1136 } catch (IOException
| InvalidMessageException e
) {
1137 System
.err
.println("Failed to retrieve attachment (" + attachment
.getId() + "): " + e
.getMessage());
1144 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1145 final File cachePath
= new File(getMessageCachePath());
1146 if (!cachePath
.exists()) {
1149 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1150 if (!dir
.isDirectory()) {
1154 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1155 if (!fileEntry
.isFile()) {
1158 SignalServiceEnvelope envelope
;
1160 envelope
= Utils
.loadEnvelope(fileEntry
);
1161 if (envelope
== null) {
1164 } catch (IOException e
) {
1165 e
.printStackTrace();
1168 SignalServiceContent content
= null;
1169 if (!envelope
.isReceipt()) {
1171 content
= decryptMessage(envelope
);
1172 } catch (Exception e
) {
1175 handleMessage(envelope
, content
, ignoreAttachments
);
1178 handler
.handleMessage(envelope
, content
, null);
1180 Files
.delete(fileEntry
.toPath());
1181 } catch (IOException e
) {
1182 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1185 // Try to delete directory if empty
1190 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1191 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1192 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1195 if (messagePipe
== null) {
1196 messagePipe
= messageReceiver
.createMessagePipe();
1200 SignalServiceEnvelope envelope
;
1201 SignalServiceContent content
= null;
1202 Exception exception
= null;
1203 final long now
= new Date().getTime();
1205 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1207 public void onMessage(SignalServiceEnvelope envelope
) {
1208 // store message on disk, before acknowledging receipt to the server
1210 File cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1211 Utils
.storeEnvelope(envelope
, cacheFile
);
1212 } catch (IOException e
) {
1213 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1217 } catch (TimeoutException e
) {
1218 if (returnOnTimeout
)
1221 } catch (InvalidVersionException e
) {
1222 System
.err
.println("Ignoring error: " + e
.getMessage());
1225 if (!envelope
.isReceipt()) {
1227 content
= decryptMessage(envelope
);
1228 } catch (Exception e
) {
1231 handleMessage(envelope
, content
, ignoreAttachments
);
1234 if (!isMessageBlocked(envelope
, content
)) {
1235 handler
.handleMessage(envelope
, content
, exception
);
1237 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1238 File cacheFile
= null;
1240 cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1241 Files
.delete(cacheFile
.toPath());
1242 // Try to delete directory if empty
1243 new File(getMessageCachePath()).delete();
1244 } catch (IOException e
) {
1245 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1250 if (messagePipe
!= null) {
1251 messagePipe
.shutdown();
1257 private boolean isMessageBlocked(SignalServiceEnvelope envelope
, SignalServiceContent content
) {
1258 SignalServiceAddress source
;
1259 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1260 source
= envelope
.getSourceAddress();
1261 } else if (content
!= null) {
1262 source
= content
.getSender();
1266 ContactInfo sourceContact
= getContact(source
.getNumber().get());
1267 if (sourceContact
!= null && sourceContact
.blocked
) {
1271 if (content
!= null && content
.getDataMessage().isPresent()) {
1272 SignalServiceDataMessage message
= content
.getDataMessage().get();
1273 if (message
.getGroupInfo().isPresent()) {
1274 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1275 GroupInfo group
= getGroup(groupInfo
.getGroupId());
1276 if (groupInfo
.getType() == SignalServiceGroup
.Type
.DELIVER
&& group
!= null && group
.blocked
) {
1284 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1285 if (content
!= null) {
1286 SignalServiceAddress sender
;
1287 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1288 sender
= envelope
.getSourceAddress();
1290 sender
= content
.getSender();
1292 if (content
.getDataMessage().isPresent()) {
1293 SignalServiceDataMessage message
= content
.getDataMessage().get();
1294 handleSignalServiceDataMessage(message
, false, sender
.getNumber().get(), getSelfAddress(), ignoreAttachments
);
1296 if (content
.getSyncMessage().isPresent()) {
1297 account
.setMultiDevice(true);
1298 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1299 if (syncMessage
.getSent().isPresent()) {
1300 SentTranscriptMessage message
= syncMessage
.getSent().get();
1301 handleSignalServiceDataMessage(message
.getMessage(), true, sender
.getNumber().get(), message
.getDestination().orNull(), ignoreAttachments
);
1303 if (syncMessage
.getRequest().isPresent()) {
1304 RequestMessage rm
= syncMessage
.getRequest().get();
1305 if (rm
.isContactsRequest()) {
1308 } catch (UntrustedIdentityException
| IOException e
) {
1309 e
.printStackTrace();
1312 if (rm
.isGroupsRequest()) {
1315 } catch (UntrustedIdentityException
| IOException e
) {
1316 e
.printStackTrace();
1319 if (rm
.isBlockedListRequest()) {
1322 } catch (UntrustedIdentityException
| IOException e
) {
1323 e
.printStackTrace();
1326 // TODO Handle rm.isConfigurationRequest();
1328 if (syncMessage
.getGroups().isPresent()) {
1329 File tmpFile
= null;
1331 tmpFile
= IOUtils
.createTempFile();
1332 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1333 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1335 while ((g
= s
.read()) != null) {
1336 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1337 if (syncGroup
== null) {
1338 syncGroup
= new GroupInfo(g
.getId());
1340 if (g
.getName().isPresent()) {
1341 syncGroup
.name
= g
.getName().get();
1343 syncGroup
.addMembers(g
.getMembers());
1344 syncGroup
.active
= g
.isActive();
1345 syncGroup
.blocked
= g
.isBlocked();
1346 if (g
.getColor().isPresent()) {
1347 syncGroup
.color
= g
.getColor().get();
1350 if (g
.getAvatar().isPresent()) {
1351 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1353 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1354 syncGroup
.archived
= g
.isArchived();
1355 account
.getGroupStore().updateGroup(syncGroup
);
1358 } catch (Exception e
) {
1359 e
.printStackTrace();
1361 if (tmpFile
!= null) {
1363 Files
.delete(tmpFile
.toPath());
1364 } catch (IOException e
) {
1365 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1370 if (syncMessage
.getBlockedList().isPresent()) {
1371 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1372 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1373 if (address
.getNumber().isPresent()) {
1375 setContactBlocked(address
.getNumber().get(), true);
1376 } catch (InvalidNumberException e
) {
1377 e
.printStackTrace();
1381 for (byte[] groupId
: blockedListMessage
.getGroupIds()) {
1383 setGroupBlocked(groupId
, true);
1384 } catch (GroupNotFoundException e
) {
1385 System
.err
.println("BlockedListMessage contained groupID that was not found in GroupStore: " + Base64
.encodeBytes(groupId
));
1389 if (syncMessage
.getContacts().isPresent()) {
1390 File tmpFile
= null;
1392 tmpFile
= IOUtils
.createTempFile();
1393 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1394 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1395 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1396 if (contactsMessage
.isComplete()) {
1397 account
.getContactStore().clear();
1400 while ((c
= s
.read()) != null) {
1401 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1402 account
.setProfileKey(c
.getProfileKey().get());
1404 ContactInfo contact
= account
.getContactStore().getContact(c
.getAddress().getNumber().get());
1405 if (contact
== null) {
1406 contact
= new ContactInfo();
1407 contact
.number
= c
.getAddress().getNumber().get();
1409 if (c
.getName().isPresent()) {
1410 contact
.name
= c
.getName().get();
1412 if (c
.getColor().isPresent()) {
1413 contact
.color
= c
.getColor().get();
1415 if (c
.getProfileKey().isPresent()) {
1416 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1418 if (c
.getVerified().isPresent()) {
1419 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1420 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1422 if (c
.getExpirationTimer().isPresent()) {
1423 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getAddress().getNumber().get());
1424 if (thread
== null) {
1425 thread
= new ThreadInfo();
1426 thread
.id
= c
.getAddress().getNumber().get();
1428 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1429 account
.getThreadStore().updateThread(thread
);
1431 contact
.blocked
= c
.isBlocked();
1432 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1433 contact
.archived
= c
.isArchived();
1434 account
.getContactStore().updateContact(contact
);
1436 if (c
.getAvatar().isPresent()) {
1437 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1441 } catch (Exception e
) {
1442 e
.printStackTrace();
1444 if (tmpFile
!= null) {
1446 Files
.delete(tmpFile
.toPath());
1447 } catch (IOException e
) {
1448 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1453 if (syncMessage
.getVerified().isPresent()) {
1454 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1455 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1457 if (syncMessage
.getConfiguration().isPresent()) {
1464 private File
getContactAvatarFile(String number
) {
1465 return new File(avatarsPath
, "contact-" + number
);
1468 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1469 IOUtils
.createPrivateDirectories(avatarsPath
);
1470 if (attachment
.isPointer()) {
1471 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1472 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1474 SignalServiceAttachmentStream stream
= attachment
.asStream();
1475 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1479 private File
getGroupAvatarFile(byte[] groupId
) {
1480 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1483 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1484 IOUtils
.createPrivateDirectories(avatarsPath
);
1485 if (attachment
.isPointer()) {
1486 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1487 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1489 SignalServiceAttachmentStream stream
= attachment
.asStream();
1490 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1494 public File
getAttachmentFile(long attachmentId
) {
1495 return new File(attachmentsPath
, attachmentId
+ "");
1498 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1499 IOUtils
.createPrivateDirectories(attachmentsPath
);
1500 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1503 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1504 if (storePreview
&& pointer
.getPreview().isPresent()) {
1505 File previewFile
= new File(outputFile
+ ".preview");
1506 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1507 byte[] preview
= pointer
.getPreview().get();
1508 output
.write(preview
, 0, preview
.length
);
1509 } catch (FileNotFoundException e
) {
1510 e
.printStackTrace();
1515 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1517 File tmpFile
= IOUtils
.createTempFile();
1518 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1519 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1520 byte[] buffer
= new byte[4096];
1523 while ((read
= input
.read(buffer
)) != -1) {
1524 output
.write(buffer
, 0, read
);
1526 } catch (FileNotFoundException e
) {
1527 e
.printStackTrace();
1532 Files
.delete(tmpFile
.toPath());
1533 } catch (IOException e
) {
1534 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1540 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1541 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1542 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1546 public boolean isRemote() {
1550 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1551 File groupsFile
= IOUtils
.createTempFile();
1554 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1555 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1556 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1557 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1558 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1559 new ArrayList
<>(record.getMembers()), createGroupAvatarAttachment(record.groupId
),
1560 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1561 Optional
.fromNullable(record.color
), record.blocked
, Optional
.fromNullable(record.inboxPosition
), record.archived
));
1565 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1566 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1567 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1568 .withStream(groupsFileStream
)
1569 .withContentType("application/octet-stream")
1570 .withLength(groupsFile
.length())
1573 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1578 Files
.delete(groupsFile
.toPath());
1579 } catch (IOException e
) {
1580 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1585 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1586 File contactsFile
= IOUtils
.createTempFile();
1589 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1590 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1591 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1592 VerifiedMessage verifiedMessage
= null;
1593 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1594 if (getIdentities().containsKey(record.number
)) {
1595 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1596 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1597 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1598 currentIdentity
= id
;
1601 if (currentIdentity
!= null) {
1602 verifiedMessage
= new VerifiedMessage(record.getAddress(), currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1606 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1607 out
.write(new DeviceContact(record.getAddress(), Optional
.fromNullable(record.name
),
1608 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1609 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), record.blocked
,
1610 Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1611 Optional
.fromNullable(record.inboxPosition
), record.archived
));
1614 if (account
.getProfileKey() != null) {
1615 // Send our own profile key as well
1616 out
.write(new DeviceContact(account
.getSelfAddress(),
1617 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1618 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1619 Optional
.of(account
.getProfileKey()),
1620 false, Optional
.<Integer
>absent(), Optional
.<Integer
>absent(), false));
1624 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1625 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1626 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1627 .withStream(contactsFileStream
)
1628 .withContentType("application/octet-stream")
1629 .withLength(contactsFile
.length())
1632 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1637 Files
.delete(contactsFile
.toPath());
1638 } catch (IOException e
) {
1639 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1644 private void sendBlockedList() throws IOException
, UntrustedIdentityException
{
1645 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
1646 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1647 if (record.blocked
) {
1648 addresses
.add(record.getAddress());
1651 List
<byte[]> groupIds
= new ArrayList
<>();
1652 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1653 if (record.blocked
) {
1654 groupIds
.add(record.groupId
);
1657 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
1660 private void sendVerifiedMessage(SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1661 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1662 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1665 public List
<ContactInfo
> getContacts() {
1666 return account
.getContactStore().getContacts();
1669 public ContactInfo
getContact(String number
) {
1670 return account
.getContactStore().getContact(number
);
1673 public GroupInfo
getGroup(byte[] groupId
) {
1674 return account
.getGroupStore().getGroup(groupId
);
1677 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1678 return account
.getSignalProtocolStore().getIdentities();
1681 public Pair
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities(String number
) throws InvalidNumberException
{
1682 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
1683 return new Pair
<>(canonicalizedNumber
, account
.getSignalProtocolStore().getIdentities(canonicalizedNumber
));
1687 * Trust this the identity with this fingerprint
1689 * @param name username of the identity
1690 * @param fingerprint Fingerprint
1692 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1693 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1697 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1698 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1702 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1704 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1705 } catch (IOException
| UntrustedIdentityException e
) {
1706 e
.printStackTrace();
1715 * Trust this the identity with this safety number
1717 * @param name username of the identity
1718 * @param safetyNumber Safety number
1720 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1721 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1725 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1726 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1730 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1732 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1733 } catch (IOException
| UntrustedIdentityException e
) {
1734 e
.printStackTrace();
1743 * Trust all keys of this identity without verification
1745 * @param name username of the identity
1747 public boolean trustIdentityAllKeys(String name
) {
1748 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1752 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1753 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1754 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1756 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1757 } catch (IOException
| UntrustedIdentityException e
) {
1758 e
.printStackTrace();
1766 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1767 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1770 public interface ReceiveMessageHandler
{
1772 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);