2 Copyright (C) 2015-2021 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
.manager
.actions
.HandleAction
;
20 import org
.asamk
.signal
.manager
.api
.Device
;
21 import org
.asamk
.signal
.manager
.api
.Message
;
22 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
23 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
24 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
25 import org
.asamk
.signal
.manager
.api
.TypingAction
;
26 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
27 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
28 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
29 import org
.asamk
.signal
.manager
.groups
.GroupId
;
30 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
31 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
32 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
33 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
34 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
35 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
36 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
37 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
38 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
39 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
40 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
41 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
42 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
43 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
44 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
45 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
46 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
47 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
48 import org
.asamk
.signal
.manager
.jobs
.Context
;
49 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
50 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
51 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
52 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
53 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
57 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
58 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
59 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
60 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
61 import org
.asamk
.signal
.manager
.util
.Utils
;
62 import org
.slf4j
.Logger
;
63 import org
.slf4j
.LoggerFactory
;
64 import org
.whispersystems
.libsignal
.IdentityKey
;
65 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
66 import org
.whispersystems
.libsignal
.InvalidKeyException
;
67 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
68 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
69 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
70 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
71 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
72 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
73 import org
.whispersystems
.libsignal
.util
.Pair
;
74 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
75 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
76 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
78 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
79 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
80 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
81 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
82 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
83 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
84 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
85 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
86 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
87 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
88 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
89 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
90 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
91 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
92 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
93 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
94 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
95 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
97 import java
.io
.Closeable
;
99 import java
.io
.IOException
;
101 import java
.net
.URISyntaxException
;
102 import java
.net
.URLEncoder
;
103 import java
.nio
.charset
.StandardCharsets
;
104 import java
.security
.SignatureException
;
105 import java
.util
.Arrays
;
106 import java
.util
.Collection
;
107 import java
.util
.Date
;
108 import java
.util
.HashMap
;
109 import java
.util
.HashSet
;
110 import java
.util
.List
;
111 import java
.util
.Map
;
112 import java
.util
.Set
;
113 import java
.util
.UUID
;
114 import java
.util
.concurrent
.ExecutorService
;
115 import java
.util
.concurrent
.Executors
;
116 import java
.util
.concurrent
.TimeUnit
;
117 import java
.util
.concurrent
.TimeoutException
;
118 import java
.util
.concurrent
.locks
.ReentrantLock
;
119 import java
.util
.function
.Function
;
120 import java
.util
.stream
.Collectors
;
122 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
124 public class Manager
implements Closeable
{
126 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
128 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
129 private final SignalDependencies dependencies
;
131 private SignalAccount account
;
133 private final ExecutorService executor
= Executors
.newCachedThreadPool();
135 private final ProfileHelper profileHelper
;
136 private final PinHelper pinHelper
;
137 private final StorageHelper storageHelper
;
138 private final SendHelper sendHelper
;
139 private final SyncHelper syncHelper
;
140 private final AttachmentHelper attachmentHelper
;
141 private final GroupHelper groupHelper
;
142 private final ContactHelper contactHelper
;
143 private final IncomingMessageHandler incomingMessageHandler
;
145 private final Context context
;
146 private boolean hasCaughtUpWithOldMessages
= false;
149 SignalAccount account
,
150 PathConfig pathConfig
,
151 ServiceEnvironmentConfig serviceEnvironmentConfig
,
154 this.account
= account
;
155 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
157 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
158 account
.getUsername(),
159 account
.getPassword(),
160 account
.getDeviceId());
161 final var sessionLock
= new SignalSessionLock() {
162 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
165 public Lock
acquire() {
167 return LEGACY_LOCK
::unlock
;
170 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
173 account
.getSignalProtocolStore(),
176 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
177 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
178 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
180 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
181 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
182 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
183 account
.getProfileStore()::getProfileKey
,
184 this::getRecipientProfile
,
185 this::getSenderCertificate
);
186 this.profileHelper
= new ProfileHelper(account
,
189 account
.getProfileStore()::getProfileKey
,
190 unidentifiedAccessHelper
::getAccessFor
,
191 this::resolveSignalServiceAddress
);
192 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
193 this::getRecipientProfile
,
194 account
::getSelfRecipientId
,
195 dependencies
.getGroupsV2Operations(),
196 dependencies
.getGroupsV2Api(),
197 this::resolveSignalServiceAddress
);
198 this.sendHelper
= new SendHelper(account
,
200 unidentifiedAccessHelper
,
201 this::resolveSignalServiceAddress
,
202 account
.getRecipientStore(),
203 this::handleIdentityFailure
,
205 this::refreshRegisteredUser
);
206 this.groupHelper
= new GroupHelper(account
,
212 this::resolveSignalServiceAddress
,
213 account
.getRecipientStore());
214 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
);
215 this.contactHelper
= new ContactHelper(account
);
216 this.syncHelper
= new SyncHelper(account
,
221 this::resolveSignalServiceAddress
);
223 this.context
= new Context(account
,
231 var jobExecutor
= new JobExecutor(context
);
233 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
235 account
.getRecipientStore(),
236 this::resolveSignalServiceAddress
,
244 public String
getUsername() {
245 return account
.getUsername();
248 public RecipientId
getSelfRecipientId() {
249 return account
.getSelfRecipientId();
252 private IdentityKeyPair
getIdentityKeyPair() {
253 return account
.getIdentityKeyPair();
256 public int getDeviceId() {
257 return account
.getDeviceId();
260 public static Manager
init(
263 ServiceEnvironment serviceEnvironment
,
265 final TrustNewIdentity trustNewIdentity
266 ) throws IOException
, NotRegisteredException
{
267 var pathConfig
= PathConfig
.createDefault(settingsPath
);
269 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
270 throw new NotRegisteredException();
273 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
275 if (!account
.isRegistered()) {
276 throw new NotRegisteredException();
279 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
281 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
284 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
285 var pathConfig
= PathConfig
.createDefault(settingsPath
);
286 final var dataPath
= pathConfig
.getDataPath();
287 final var files
= dataPath
.listFiles();
293 return Arrays
.stream(files
)
294 .filter(File
::isFile
)
296 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
297 .collect(Collectors
.toList());
300 public void checkAccountState() throws IOException
{
301 if (account
.getLastReceiveTimestamp() == 0) {
302 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
304 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
305 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
308 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
312 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
315 if (account
.getUuid() == null) {
316 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
318 updateAccountAttributes(null);
322 * This is used for checking a set of phone numbers for registration on Signal
324 * @param numbers The set of phone number in question
325 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
326 * @throws IOException if its unable to get the contacts to check if they're registered
328 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
329 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
331 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
332 } catch (InvalidNumberException e
) {
337 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
338 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
340 .filter(s
-> !s
.isEmpty())
341 .collect(Collectors
.toSet()));
343 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
344 final var number
= canonicalizedNumbers
.get(n
);
345 final var uuid
= registeredUsers
.get(number
);
346 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
350 public void updateAccountAttributes(String deviceName
) throws IOException
{
351 final String encryptedDeviceName
;
352 if (deviceName
== null) {
353 encryptedDeviceName
= account
.getEncryptedDeviceName();
355 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
356 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
357 account
.setEncryptedDeviceName(encryptedDeviceName
);
359 dependencies
.getAccountManager()
360 .setAccountAttributes(encryptedDeviceName
,
362 account
.getLocalRegistrationId(),
365 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
366 account
.getSelfUnidentifiedAccessKey(),
367 account
.isUnrestrictedUnidentifiedAccess(),
369 account
.isDiscoverableByPhoneNumber());
373 * @param givenName if null, the previous givenName will be kept
374 * @param familyName if null, the previous familyName will be kept
375 * @param about if null, the previous about text will be kept
376 * @param aboutEmoji if null, the previous about emoji will be kept
377 * @param avatar if avatar is null the image from the local avatar store is used (if present),
379 public void setProfile(
380 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
381 ) throws IOException
{
382 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
383 syncHelper
.sendSyncFetchProfileMessage();
386 public void unregister() throws IOException
{
387 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
388 // If this is the master device, other users can't send messages to this number anymore.
389 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
390 dependencies
.getAccountManager().setGcmId(Optional
.absent());
392 account
.setRegistered(false);
395 public void deleteAccount() throws IOException
{
397 pinHelper
.removeRegistrationLockPin();
398 } catch (UnauthenticatedResponseException e
) {
399 logger
.warn("Failed to remove registration lock pin");
401 account
.setRegistrationLockPin(null, null);
403 dependencies
.getAccountManager().deleteAccount();
405 account
.setRegistered(false);
408 public List
<Device
> getLinkedDevices() throws IOException
{
409 var devices
= dependencies
.getAccountManager().getDevices();
410 account
.setMultiDevice(devices
.size() > 1);
411 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
412 return devices
.stream().map(d
-> {
413 String deviceName
= d
.getName();
414 if (deviceName
!= null) {
416 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
417 } catch (IOException e
) {
418 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
421 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
422 }).collect(Collectors
.toList());
425 public void removeLinkedDevices(int deviceId
) throws IOException
{
426 dependencies
.getAccountManager().removeDevice(deviceId
);
427 var devices
= dependencies
.getAccountManager().getDevices();
428 account
.setMultiDevice(devices
.size() > 1);
431 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
432 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
434 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
437 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
438 var identityKeyPair
= getIdentityKeyPair();
439 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
441 dependencies
.getAccountManager()
442 .addDevice(deviceIdentifier
,
445 Optional
.of(account
.getProfileKey().serialize()),
447 account
.setMultiDevice(true);
450 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
451 if (!account
.isMasterDevice()) {
452 throw new RuntimeException("Only master device can set a PIN");
454 if (pin
.isPresent()) {
455 final var masterKey
= account
.getPinMasterKey() != null
456 ? account
.getPinMasterKey()
457 : KeyUtils
.createMasterKey();
459 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
461 account
.setRegistrationLockPin(pin
.get(), masterKey
);
464 pinHelper
.removeRegistrationLockPin();
466 account
.setRegistrationLockPin(null, null);
470 void refreshPreKeys() throws IOException
{
471 var oneTimePreKeys
= generatePreKeys();
472 final var identityKeyPair
= getIdentityKeyPair();
473 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
475 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
478 private List
<PreKeyRecord
> generatePreKeys() {
479 final var offset
= account
.getPreKeyIdOffset();
481 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
482 account
.addPreKeys(records
);
487 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
488 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
490 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
491 account
.addSignedPreKey(record);
496 public Profile
getRecipientProfile(RecipientId recipientId
) {
497 return profileHelper
.getRecipientProfile(recipientId
);
500 public List
<GroupInfo
> getGroups() {
501 return account
.getGroupStore().getGroups();
504 public SendGroupMessageResults
quitGroup(
505 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
506 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
507 final var newAdmins
= resolveRecipients(groupAdmins
);
508 return groupHelper
.quitGroup(groupId
, newAdmins
);
511 public void deleteGroup(GroupId groupId
) throws IOException
{
512 groupHelper
.deleteGroup(groupId
);
515 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
516 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
517 ) throws IOException
, AttachmentInvalidException
{
518 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
521 public SendGroupMessageResults
updateGroup(
525 Set
<RecipientIdentifier
.Single
> members
,
526 Set
<RecipientIdentifier
.Single
> removeMembers
,
527 Set
<RecipientIdentifier
.Single
> admins
,
528 Set
<RecipientIdentifier
.Single
> removeAdmins
,
529 boolean resetGroupLink
,
530 GroupLinkState groupLinkState
,
531 GroupPermission addMemberPermission
,
532 GroupPermission editDetailsPermission
,
534 Integer expirationTimer
,
535 Boolean isAnnouncementGroup
536 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
537 return groupHelper
.updateGroup(groupId
,
540 members
== null ?
null : resolveRecipients(members
),
541 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
542 admins
== null ?
null : resolveRecipients(admins
),
543 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
547 editDetailsPermission
,
550 isAnnouncementGroup
);
553 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
554 GroupInviteLinkUrl inviteLinkUrl
555 ) throws IOException
, GroupLinkNotActiveException
{
556 return groupHelper
.joinGroup(inviteLinkUrl
);
559 public SendMessageResults
sendMessage(
560 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
561 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
562 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
563 long timestamp
= System
.currentTimeMillis();
564 messageBuilder
.withTimestamp(timestamp
);
565 for (final var recipient
: recipients
) {
566 if (recipient
instanceof RecipientIdentifier
.Single
) {
567 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
568 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
569 results
.put(recipient
, List
.of(result
));
570 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
571 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
572 results
.put(recipient
, List
.of(result
));
573 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
574 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
575 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
576 results
.put(recipient
, result
);
579 return new SendMessageResults(timestamp
, results
);
582 public void sendTypingMessage(
583 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
584 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
585 final var timestamp
= System
.currentTimeMillis();
586 for (var recipient
: recipients
) {
587 if (recipient
instanceof RecipientIdentifier
.Single
) {
588 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
589 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
590 sendHelper
.sendTypingMessage(message
, recipientId
);
591 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
592 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
593 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
594 sendHelper
.sendGroupTypingMessage(message
, groupId
);
599 public void sendReadReceipt(
600 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
601 ) throws IOException
, UntrustedIdentityException
{
602 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
604 System
.currentTimeMillis());
606 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
609 public void sendViewedReceipt(
610 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
611 ) throws IOException
, UntrustedIdentityException
{
612 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
614 System
.currentTimeMillis());
616 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
619 public SendMessageResults
sendMessage(
620 Message message
, Set
<RecipientIdentifier
> recipients
621 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
622 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
623 applyMessage(messageBuilder
, message
);
624 return sendMessage(messageBuilder
, recipients
);
627 private void applyMessage(
628 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
629 ) throws AttachmentInvalidException
, IOException
{
630 messageBuilder
.withBody(message
.getMessageText());
631 final var attachments
= message
.getAttachments();
632 if (attachments
!= null) {
633 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
637 public SendMessageResults
sendRemoteDeleteMessage(
638 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
639 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
640 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
641 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
642 return sendMessage(messageBuilder
, recipients
);
645 public SendMessageResults
sendMessageReaction(
648 RecipientIdentifier
.Single targetAuthor
,
649 long targetSentTimestamp
,
650 Set
<RecipientIdentifier
> recipients
651 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
652 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
653 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
655 resolveSignalServiceAddress(targetAuthorRecipientId
),
656 targetSentTimestamp
);
657 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
658 return sendMessage(messageBuilder
, recipients
);
661 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
662 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
665 return sendMessage(messageBuilder
,
666 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
667 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
668 throw new AssertionError(e
);
670 for (var recipient
: recipients
) {
671 final var recipientId
= resolveRecipient(recipient
);
672 account
.getSessionStore().deleteAllSessions(recipientId
);
677 public void setContactName(
678 RecipientIdentifier
.Single recipient
, String name
679 ) throws NotMasterDeviceException
, UnregisteredUserException
{
680 if (!account
.isMasterDevice()) {
681 throw new NotMasterDeviceException();
683 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
686 public void setContactBlocked(
687 RecipientIdentifier
.Single recipient
, boolean blocked
688 ) throws NotMasterDeviceException
, IOException
{
689 if (!account
.isMasterDevice()) {
690 throw new NotMasterDeviceException();
692 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
693 // TODO cycle our profile key
694 syncHelper
.sendBlockedList();
697 public void setGroupBlocked(
698 final GroupId groupId
, final boolean blocked
699 ) throws GroupNotFoundException
, IOException
{
700 groupHelper
.setGroupBlocked(groupId
, blocked
);
701 // TODO cycle our profile key
702 syncHelper
.sendBlockedList();
706 * Change the expiration timer for a contact
708 public void setExpirationTimer(
709 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
710 ) throws IOException
{
711 var recipientId
= resolveRecipient(recipient
);
712 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
713 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
715 sendMessage(messageBuilder
, Set
.of(recipient
));
716 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
717 throw new AssertionError(e
);
722 * Upload the sticker pack from path.
724 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
725 * @return if successful, returns the URL to install the sticker pack in the signal app
727 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
728 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
730 var messageSender
= dependencies
.getMessageSender();
732 var packKey
= KeyUtils
.createStickerUploadKey();
733 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
734 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
736 var sticker
= new Sticker(packId
, packKey
);
737 account
.getStickerStore().updateSticker(sticker
);
740 return new URI("https",
744 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
746 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
747 } catch (URISyntaxException e
) {
748 throw new AssertionError(e
);
752 public void requestAllSyncData() throws IOException
{
753 syncHelper
.requestAllSyncData();
754 retrieveRemoteStorage();
757 void retrieveRemoteStorage() throws IOException
{
758 if (account
.getStorageKey() != null) {
759 storageHelper
.readDataFromStorage();
763 private byte[] getSenderCertificate() {
766 if (account
.isPhoneNumberShared()) {
767 certificate
= dependencies
.getAccountManager().getSenderCertificate();
769 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
771 } catch (IOException e
) {
772 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
775 // TODO cache for a day
779 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
780 final var address
= resolveSignalServiceAddress(recipientId
);
781 if (!address
.getNumber().isPresent()) {
784 final var number
= address
.getNumber().get();
785 final var uuid
= getRegisteredUser(number
);
786 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
789 private UUID
getRegisteredUser(final String number
) throws IOException
{
790 final Map
<String
, UUID
> uuidMap
;
792 uuidMap
= getRegisteredUsers(Set
.of(number
));
793 } catch (NumberFormatException e
) {
794 throw new UnregisteredUserException(number
, e
);
796 final var uuid
= uuidMap
.get(number
);
798 throw new UnregisteredUserException(number
, null);
803 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
804 final Map
<String
, UUID
> registeredUsers
;
806 registeredUsers
= dependencies
.getAccountManager()
807 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
809 serviceEnvironmentConfig
.getCdsMrenclave());
810 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
811 throw new IOException(e
);
814 // Store numbers as recipients so we have the number/uuid association
815 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
817 return registeredUsers
;
820 public void sendTypingMessage(
821 TypingAction action
, Set
<RecipientIdentifier
> recipients
822 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
823 sendTypingMessage(action
.toSignalService(), recipients
);
826 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
827 Set
<HandleAction
> queuedActions
= new HashSet
<>();
828 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
829 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
830 if (actions
!= null) {
831 queuedActions
.addAll(actions
);
834 handleQueuedActions(queuedActions
);
837 private List
<HandleAction
> retryFailedReceivedMessage(
838 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
840 var envelope
= cachedMessage
.loadEnvelope();
841 if (envelope
== null) {
842 cachedMessage
.delete();
846 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
847 final var actions
= result
.first();
848 final var exception
= result
.second();
850 if (exception
instanceof UntrustedIdentityException
) {
851 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
852 // Envelope is more than a month old, cleaning up.
853 cachedMessage
.delete();
856 if (!envelope
.hasSourceUuid()) {
857 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
858 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
860 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
861 } catch (IOException ioException
) {
862 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
868 // If successful and for all other errors that are not recoverable, delete the cached message
869 cachedMessage
.delete();
873 public void receiveMessages(
876 boolean returnOnTimeout
,
877 boolean ignoreAttachments
,
878 ReceiveMessageHandler handler
879 ) throws IOException
{
880 retryFailedReceivedMessages(handler
, ignoreAttachments
);
882 Set
<HandleAction
> queuedActions
= new HashSet
<>();
884 final var signalWebSocket
= dependencies
.getSignalWebSocket();
885 signalWebSocket
.connect();
887 hasCaughtUpWithOldMessages
= false;
889 while (!Thread
.interrupted()) {
890 SignalServiceEnvelope envelope
;
891 final CachedMessage
[] cachedMessage
= {null};
892 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
893 logger
.debug("Checking for new message from server");
895 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
896 final var recipientId
= envelope1
.hasSourceUuid()
897 ?
resolveRecipient(envelope1
.getSourceAddress())
899 // store message on disk, before acknowledging receipt to the server
900 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
902 logger
.debug("New message received from server");
903 if (result
.isPresent()) {
904 envelope
= result
.get();
906 // Received indicator that server queue is empty
907 handleQueuedActions(queuedActions
);
908 queuedActions
.clear();
910 hasCaughtUpWithOldMessages
= true;
911 synchronized (this) {
915 // Continue to wait another timeout for new messages
918 } catch (AssertionError e
) {
919 if (e
.getCause() instanceof InterruptedException
) {
920 Thread
.currentThread().interrupt();
925 } catch (WebSocketUnavailableException e
) {
926 logger
.debug("Pipe unexpectedly unavailable, connecting");
927 signalWebSocket
.connect();
929 } catch (TimeoutException e
) {
930 if (returnOnTimeout
) return;
934 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
935 queuedActions
.addAll(result
.first());
936 final var exception
= result
.second();
938 if (hasCaughtUpWithOldMessages
) {
939 handleQueuedActions(queuedActions
);
941 if (cachedMessage
[0] != null) {
942 if (exception
instanceof UntrustedIdentityException
) {
943 final var address
= ((UntrustedIdentityException
) exception
).getSender();
944 final var recipientId
= resolveRecipient(address
);
945 if (!envelope
.hasSourceUuid()) {
947 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
948 } catch (IOException ioException
) {
949 logger
.warn("Failed to move cached message to recipient folder: {}",
950 ioException
.getMessage());
954 cachedMessage
[0].delete();
958 handleQueuedActions(queuedActions
);
961 public boolean hasCaughtUpWithOldMessages() {
962 return hasCaughtUpWithOldMessages
;
965 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
966 var interrupted
= false;
967 for (var action
: queuedActions
) {
969 action
.execute(context
);
970 } catch (Throwable e
) {
971 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
972 && e
.getCause() instanceof InterruptedException
) {
976 logger
.warn("Message action failed.", e
);
980 Thread
.currentThread().interrupt();
984 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
985 final RecipientId recipientId
;
987 recipientId
= resolveRecipient(recipient
);
988 } catch (UnregisteredUserException e
) {
991 return contactHelper
.isContactBlocked(recipientId
);
994 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
995 return attachmentHelper
.getAttachmentFile(attachmentId
);
998 public void sendContacts() throws IOException
{
999 syncHelper
.sendContacts();
1002 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
1003 return account
.getContactStore().getContacts();
1006 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
1007 final RecipientId recipientId
;
1009 recipientId
= resolveRecipient(recipientIdentifier
);
1010 } catch (UnregisteredUserException e
) {
1014 final var contact
= account
.getContactStore().getContact(recipientId
);
1015 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1016 return contact
.getName();
1019 final var profile
= getRecipientProfile(recipientId
);
1020 if (profile
!= null) {
1021 return profile
.getDisplayName();
1027 public GroupInfo
getGroup(GroupId groupId
) {
1028 return groupHelper
.getGroup(groupId
);
1031 public List
<IdentityInfo
> getIdentities() {
1032 return account
.getIdentityKeyStore().getIdentities();
1035 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1036 IdentityInfo identity
;
1038 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1039 } catch (UnregisteredUserException e
) {
1042 return identity
== null ? List
.of() : List
.of(identity
);
1046 * Trust this the identity with this fingerprint
1048 * @param recipient username of the identity
1049 * @param fingerprint Fingerprint
1051 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1052 RecipientId recipientId
;
1054 recipientId
= resolveRecipient(recipient
);
1055 } catch (UnregisteredUserException e
) {
1058 return trustIdentity(recipientId
,
1059 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1060 TrustLevel
.TRUSTED_VERIFIED
);
1064 * Trust this the identity with this safety number
1066 * @param recipient username of the identity
1067 * @param safetyNumber Safety number
1069 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1070 RecipientId recipientId
;
1072 recipientId
= resolveRecipient(recipient
);
1073 } catch (UnregisteredUserException e
) {
1076 var address
= resolveSignalServiceAddress(recipientId
);
1077 return trustIdentity(recipientId
,
1078 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1079 TrustLevel
.TRUSTED_VERIFIED
);
1083 * Trust this the identity with this scannable safety number
1085 * @param recipient username of the identity
1086 * @param safetyNumber Scannable safety number
1088 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1089 RecipientId recipientId
;
1091 recipientId
= resolveRecipient(recipient
);
1092 } catch (UnregisteredUserException e
) {
1095 var address
= resolveSignalServiceAddress(recipientId
);
1096 return trustIdentity(recipientId
, identityKey
-> {
1097 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1099 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1100 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1103 }, TrustLevel
.TRUSTED_VERIFIED
);
1107 * Trust all keys of this identity without verification
1109 * @param recipient username of the identity
1111 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1112 RecipientId recipientId
;
1114 recipientId
= resolveRecipient(recipient
);
1115 } catch (UnregisteredUserException e
) {
1118 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1121 private boolean trustIdentity(
1122 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1124 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1125 if (identity
== null) {
1129 if (!verifier
.apply(identity
.getIdentityKey())) {
1133 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1135 var address
= resolveSignalServiceAddress(recipientId
);
1136 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1137 } catch (IOException e
) {
1138 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1144 private void handleIdentityFailure(
1145 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1147 final var identityKey
= identityFailure
.getIdentityKey();
1148 if (identityKey
!= null) {
1149 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1151 account
.getSessionStore().archiveSessions(recipientId
);
1154 // Retrieve profile to get the current identity key from the server
1155 profileHelper
.refreshRecipientProfile(recipientId
);
1159 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1160 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1161 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1164 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1165 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1166 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1169 private Fingerprint
computeSafetyNumberFingerprint(
1170 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1172 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1173 account
.getSelfAddress(),
1174 getIdentityKeyPair().getPublicKey(),
1179 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1180 return resolveSignalServiceAddress(resolveRecipient(address
));
1183 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1184 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1187 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1188 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1189 if (address
.getUuid().isPresent()) {
1190 return address
.toSignalServiceAddress();
1193 // Address in recipient store doesn't have a uuid, this shouldn't happen
1194 // Try to retrieve the uuid from the server
1195 final var number
= address
.getNumber().get();
1197 return resolveSignalServiceAddress(getRegisteredUser(number
));
1198 } catch (IOException e
) {
1199 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1200 // Return SignalServiceAddress with unknown UUID
1201 return address
.toSignalServiceAddress();
1205 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1206 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1207 for (var number
: recipients
) {
1208 final var recipientId
= resolveRecipient(number
);
1209 recipientIds
.add(recipientId
);
1211 return recipientIds
;
1214 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1215 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1216 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1218 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1219 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1221 return getRegisteredUser(number
);
1222 } catch (IOException e
) {
1229 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1230 return account
.getRecipientStore().resolveRecipient(address
);
1233 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1234 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1238 public void close() throws IOException
{
1242 private void close(boolean closeAccount
) throws IOException
{
1243 executor
.shutdown();
1245 dependencies
.getSignalWebSocket().disconnect();
1247 if (closeAccount
&& account
!= null) {
1253 public interface ReceiveMessageHandler
{
1255 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);