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 void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
409 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
412 public List
<Device
> getLinkedDevices() throws IOException
{
413 var devices
= dependencies
.getAccountManager().getDevices();
414 account
.setMultiDevice(devices
.size() > 1);
415 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
416 return devices
.stream().map(d
-> {
417 String deviceName
= d
.getName();
418 if (deviceName
!= null) {
420 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
421 } catch (IOException e
) {
422 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
425 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
426 }).collect(Collectors
.toList());
429 public void removeLinkedDevices(int deviceId
) throws IOException
{
430 dependencies
.getAccountManager().removeDevice(deviceId
);
431 var devices
= dependencies
.getAccountManager().getDevices();
432 account
.setMultiDevice(devices
.size() > 1);
435 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
436 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
438 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
441 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
442 var identityKeyPair
= getIdentityKeyPair();
443 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
445 dependencies
.getAccountManager()
446 .addDevice(deviceIdentifier
,
449 Optional
.of(account
.getProfileKey().serialize()),
451 account
.setMultiDevice(true);
454 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
455 if (!account
.isMasterDevice()) {
456 throw new RuntimeException("Only master device can set a PIN");
458 if (pin
.isPresent()) {
459 final var masterKey
= account
.getPinMasterKey() != null
460 ? account
.getPinMasterKey()
461 : KeyUtils
.createMasterKey();
463 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
465 account
.setRegistrationLockPin(pin
.get(), masterKey
);
468 pinHelper
.removeRegistrationLockPin();
470 account
.setRegistrationLockPin(null, null);
474 void refreshPreKeys() throws IOException
{
475 var oneTimePreKeys
= generatePreKeys();
476 final var identityKeyPair
= getIdentityKeyPair();
477 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
479 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
482 private List
<PreKeyRecord
> generatePreKeys() {
483 final var offset
= account
.getPreKeyIdOffset();
485 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
486 account
.addPreKeys(records
);
491 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
492 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
494 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
495 account
.addSignedPreKey(record);
500 public Profile
getRecipientProfile(RecipientId recipientId
) {
501 return profileHelper
.getRecipientProfile(recipientId
);
504 public List
<GroupInfo
> getGroups() {
505 return account
.getGroupStore().getGroups();
508 public SendGroupMessageResults
quitGroup(
509 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
510 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
511 final var newAdmins
= resolveRecipients(groupAdmins
);
512 return groupHelper
.quitGroup(groupId
, newAdmins
);
515 public void deleteGroup(GroupId groupId
) throws IOException
{
516 groupHelper
.deleteGroup(groupId
);
519 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
520 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
521 ) throws IOException
, AttachmentInvalidException
{
522 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
525 public SendGroupMessageResults
updateGroup(
529 Set
<RecipientIdentifier
.Single
> members
,
530 Set
<RecipientIdentifier
.Single
> removeMembers
,
531 Set
<RecipientIdentifier
.Single
> admins
,
532 Set
<RecipientIdentifier
.Single
> removeAdmins
,
533 boolean resetGroupLink
,
534 GroupLinkState groupLinkState
,
535 GroupPermission addMemberPermission
,
536 GroupPermission editDetailsPermission
,
538 Integer expirationTimer
,
539 Boolean isAnnouncementGroup
540 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
541 return groupHelper
.updateGroup(groupId
,
544 members
== null ?
null : resolveRecipients(members
),
545 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
546 admins
== null ?
null : resolveRecipients(admins
),
547 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
551 editDetailsPermission
,
554 isAnnouncementGroup
);
557 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
558 GroupInviteLinkUrl inviteLinkUrl
559 ) throws IOException
, GroupLinkNotActiveException
{
560 return groupHelper
.joinGroup(inviteLinkUrl
);
563 public SendMessageResults
sendMessage(
564 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
565 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
566 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
567 long timestamp
= System
.currentTimeMillis();
568 messageBuilder
.withTimestamp(timestamp
);
569 for (final var recipient
: recipients
) {
570 if (recipient
instanceof RecipientIdentifier
.Single
) {
571 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
572 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
573 results
.put(recipient
, List
.of(result
));
574 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
575 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
576 results
.put(recipient
, List
.of(result
));
577 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
578 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
579 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
580 results
.put(recipient
, result
);
583 return new SendMessageResults(timestamp
, results
);
586 public void sendTypingMessage(
587 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
588 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
589 final var timestamp
= System
.currentTimeMillis();
590 for (var recipient
: recipients
) {
591 if (recipient
instanceof RecipientIdentifier
.Single
) {
592 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
593 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
594 sendHelper
.sendTypingMessage(message
, recipientId
);
595 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
596 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
597 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
598 sendHelper
.sendGroupTypingMessage(message
, groupId
);
603 public void sendReadReceipt(
604 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
605 ) throws IOException
, UntrustedIdentityException
{
606 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
608 System
.currentTimeMillis());
610 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
613 public void sendViewedReceipt(
614 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
615 ) throws IOException
, UntrustedIdentityException
{
616 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
618 System
.currentTimeMillis());
620 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
623 public SendMessageResults
sendMessage(
624 Message message
, Set
<RecipientIdentifier
> recipients
625 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
626 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
627 applyMessage(messageBuilder
, message
);
628 return sendMessage(messageBuilder
, recipients
);
631 private void applyMessage(
632 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
633 ) throws AttachmentInvalidException
, IOException
{
634 messageBuilder
.withBody(message
.getMessageText());
635 final var attachments
= message
.getAttachments();
636 if (attachments
!= null) {
637 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
641 public SendMessageResults
sendRemoteDeleteMessage(
642 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
643 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
644 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
645 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
646 return sendMessage(messageBuilder
, recipients
);
649 public SendMessageResults
sendMessageReaction(
652 RecipientIdentifier
.Single targetAuthor
,
653 long targetSentTimestamp
,
654 Set
<RecipientIdentifier
> recipients
655 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
656 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
657 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
659 resolveSignalServiceAddress(targetAuthorRecipientId
),
660 targetSentTimestamp
);
661 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
662 return sendMessage(messageBuilder
, recipients
);
665 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
666 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
669 return sendMessage(messageBuilder
,
670 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
671 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
672 throw new AssertionError(e
);
674 for (var recipient
: recipients
) {
675 final var recipientId
= resolveRecipient(recipient
);
676 account
.getSessionStore().deleteAllSessions(recipientId
);
681 public void setContactName(
682 RecipientIdentifier
.Single recipient
, String name
683 ) throws NotMasterDeviceException
, UnregisteredUserException
{
684 if (!account
.isMasterDevice()) {
685 throw new NotMasterDeviceException();
687 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
690 public void setContactBlocked(
691 RecipientIdentifier
.Single recipient
, boolean blocked
692 ) throws NotMasterDeviceException
, IOException
{
693 if (!account
.isMasterDevice()) {
694 throw new NotMasterDeviceException();
696 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
697 // TODO cycle our profile key
698 syncHelper
.sendBlockedList();
701 public void setGroupBlocked(
702 final GroupId groupId
, final boolean blocked
703 ) throws GroupNotFoundException
, IOException
{
704 groupHelper
.setGroupBlocked(groupId
, blocked
);
705 // TODO cycle our profile key
706 syncHelper
.sendBlockedList();
710 * Change the expiration timer for a contact
712 public void setExpirationTimer(
713 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
714 ) throws IOException
{
715 var recipientId
= resolveRecipient(recipient
);
716 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
717 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
719 sendMessage(messageBuilder
, Set
.of(recipient
));
720 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
721 throw new AssertionError(e
);
726 * Upload the sticker pack from path.
728 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
729 * @return if successful, returns the URL to install the sticker pack in the signal app
731 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
732 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
734 var messageSender
= dependencies
.getMessageSender();
736 var packKey
= KeyUtils
.createStickerUploadKey();
737 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
738 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
740 var sticker
= new Sticker(packId
, packKey
);
741 account
.getStickerStore().updateSticker(sticker
);
744 return new URI("https",
748 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
750 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
751 } catch (URISyntaxException e
) {
752 throw new AssertionError(e
);
756 public void requestAllSyncData() throws IOException
{
757 syncHelper
.requestAllSyncData();
758 retrieveRemoteStorage();
761 void retrieveRemoteStorage() throws IOException
{
762 if (account
.getStorageKey() != null) {
763 storageHelper
.readDataFromStorage();
767 private byte[] getSenderCertificate() {
770 if (account
.isPhoneNumberShared()) {
771 certificate
= dependencies
.getAccountManager().getSenderCertificate();
773 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
775 } catch (IOException e
) {
776 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
779 // TODO cache for a day
783 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
784 final var address
= resolveSignalServiceAddress(recipientId
);
785 if (!address
.getNumber().isPresent()) {
788 final var number
= address
.getNumber().get();
789 final var uuid
= getRegisteredUser(number
);
790 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
793 private UUID
getRegisteredUser(final String number
) throws IOException
{
794 final Map
<String
, UUID
> uuidMap
;
796 uuidMap
= getRegisteredUsers(Set
.of(number
));
797 } catch (NumberFormatException e
) {
798 throw new UnregisteredUserException(number
, e
);
800 final var uuid
= uuidMap
.get(number
);
802 throw new UnregisteredUserException(number
, null);
807 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
808 final Map
<String
, UUID
> registeredUsers
;
810 registeredUsers
= dependencies
.getAccountManager()
811 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
813 serviceEnvironmentConfig
.getCdsMrenclave());
814 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
815 throw new IOException(e
);
818 // Store numbers as recipients so we have the number/uuid association
819 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
821 return registeredUsers
;
824 public void sendTypingMessage(
825 TypingAction action
, Set
<RecipientIdentifier
> recipients
826 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
827 sendTypingMessage(action
.toSignalService(), recipients
);
830 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
831 Set
<HandleAction
> queuedActions
= new HashSet
<>();
832 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
833 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
834 if (actions
!= null) {
835 queuedActions
.addAll(actions
);
838 handleQueuedActions(queuedActions
);
841 private List
<HandleAction
> retryFailedReceivedMessage(
842 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
844 var envelope
= cachedMessage
.loadEnvelope();
845 if (envelope
== null) {
846 cachedMessage
.delete();
850 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
851 final var actions
= result
.first();
852 final var exception
= result
.second();
854 if (exception
instanceof UntrustedIdentityException
) {
855 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
856 // Envelope is more than a month old, cleaning up.
857 cachedMessage
.delete();
860 if (!envelope
.hasSourceUuid()) {
861 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
862 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
864 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
865 } catch (IOException ioException
) {
866 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
872 // If successful and for all other errors that are not recoverable, delete the cached message
873 cachedMessage
.delete();
877 public void receiveMessages(
880 boolean returnOnTimeout
,
881 boolean ignoreAttachments
,
882 ReceiveMessageHandler handler
883 ) throws IOException
{
884 retryFailedReceivedMessages(handler
, ignoreAttachments
);
886 Set
<HandleAction
> queuedActions
= new HashSet
<>();
888 final var signalWebSocket
= dependencies
.getSignalWebSocket();
889 signalWebSocket
.connect();
891 hasCaughtUpWithOldMessages
= false;
893 while (!Thread
.interrupted()) {
894 SignalServiceEnvelope envelope
;
895 final CachedMessage
[] cachedMessage
= {null};
896 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
897 logger
.debug("Checking for new message from server");
899 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
900 final var recipientId
= envelope1
.hasSourceUuid()
901 ?
resolveRecipient(envelope1
.getSourceAddress())
903 // store message on disk, before acknowledging receipt to the server
904 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
906 logger
.debug("New message received from server");
907 if (result
.isPresent()) {
908 envelope
= result
.get();
910 // Received indicator that server queue is empty
911 handleQueuedActions(queuedActions
);
912 queuedActions
.clear();
914 hasCaughtUpWithOldMessages
= true;
915 synchronized (this) {
919 // Continue to wait another timeout for new messages
922 } catch (AssertionError e
) {
923 if (e
.getCause() instanceof InterruptedException
) {
924 Thread
.currentThread().interrupt();
929 } catch (WebSocketUnavailableException e
) {
930 logger
.debug("Pipe unexpectedly unavailable, connecting");
931 signalWebSocket
.connect();
933 } catch (TimeoutException e
) {
934 if (returnOnTimeout
) return;
938 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
939 queuedActions
.addAll(result
.first());
940 final var exception
= result
.second();
942 if (hasCaughtUpWithOldMessages
) {
943 handleQueuedActions(queuedActions
);
945 if (cachedMessage
[0] != null) {
946 if (exception
instanceof UntrustedIdentityException
) {
947 final var address
= ((UntrustedIdentityException
) exception
).getSender();
948 final var recipientId
= resolveRecipient(address
);
949 if (!envelope
.hasSourceUuid()) {
951 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
952 } catch (IOException ioException
) {
953 logger
.warn("Failed to move cached message to recipient folder: {}",
954 ioException
.getMessage());
958 cachedMessage
[0].delete();
962 handleQueuedActions(queuedActions
);
965 public boolean hasCaughtUpWithOldMessages() {
966 return hasCaughtUpWithOldMessages
;
969 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
970 var interrupted
= false;
971 for (var action
: queuedActions
) {
973 action
.execute(context
);
974 } catch (Throwable e
) {
975 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
976 && e
.getCause() instanceof InterruptedException
) {
980 logger
.warn("Message action failed.", e
);
984 Thread
.currentThread().interrupt();
988 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
989 final RecipientId recipientId
;
991 recipientId
= resolveRecipient(recipient
);
992 } catch (UnregisteredUserException e
) {
995 return contactHelper
.isContactBlocked(recipientId
);
998 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
999 return attachmentHelper
.getAttachmentFile(attachmentId
);
1002 public void sendContacts() throws IOException
{
1003 syncHelper
.sendContacts();
1006 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
1007 return account
.getContactStore().getContacts();
1010 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
1011 final RecipientId recipientId
;
1013 recipientId
= resolveRecipient(recipientIdentifier
);
1014 } catch (UnregisteredUserException e
) {
1018 final var contact
= account
.getContactStore().getContact(recipientId
);
1019 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1020 return contact
.getName();
1023 final var profile
= getRecipientProfile(recipientId
);
1024 if (profile
!= null) {
1025 return profile
.getDisplayName();
1031 public GroupInfo
getGroup(GroupId groupId
) {
1032 return groupHelper
.getGroup(groupId
);
1035 public List
<IdentityInfo
> getIdentities() {
1036 return account
.getIdentityKeyStore().getIdentities();
1039 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1040 IdentityInfo identity
;
1042 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1043 } catch (UnregisteredUserException e
) {
1046 return identity
== null ? List
.of() : List
.of(identity
);
1050 * Trust this the identity with this fingerprint
1052 * @param recipient username of the identity
1053 * @param fingerprint Fingerprint
1055 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1056 RecipientId recipientId
;
1058 recipientId
= resolveRecipient(recipient
);
1059 } catch (UnregisteredUserException e
) {
1062 return trustIdentity(recipientId
,
1063 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1064 TrustLevel
.TRUSTED_VERIFIED
);
1068 * Trust this the identity with this safety number
1070 * @param recipient username of the identity
1071 * @param safetyNumber Safety number
1073 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1074 RecipientId recipientId
;
1076 recipientId
= resolveRecipient(recipient
);
1077 } catch (UnregisteredUserException e
) {
1080 var address
= resolveSignalServiceAddress(recipientId
);
1081 return trustIdentity(recipientId
,
1082 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1083 TrustLevel
.TRUSTED_VERIFIED
);
1087 * Trust this the identity with this scannable safety number
1089 * @param recipient username of the identity
1090 * @param safetyNumber Scannable safety number
1092 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1093 RecipientId recipientId
;
1095 recipientId
= resolveRecipient(recipient
);
1096 } catch (UnregisteredUserException e
) {
1099 var address
= resolveSignalServiceAddress(recipientId
);
1100 return trustIdentity(recipientId
, identityKey
-> {
1101 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1103 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1104 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1107 }, TrustLevel
.TRUSTED_VERIFIED
);
1111 * Trust all keys of this identity without verification
1113 * @param recipient username of the identity
1115 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1116 RecipientId recipientId
;
1118 recipientId
= resolveRecipient(recipient
);
1119 } catch (UnregisteredUserException e
) {
1122 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1125 private boolean trustIdentity(
1126 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1128 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1129 if (identity
== null) {
1133 if (!verifier
.apply(identity
.getIdentityKey())) {
1137 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1139 var address
= resolveSignalServiceAddress(recipientId
);
1140 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1141 } catch (IOException e
) {
1142 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1148 private void handleIdentityFailure(
1149 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1151 final var identityKey
= identityFailure
.getIdentityKey();
1152 if (identityKey
!= null) {
1153 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1155 account
.getSessionStore().archiveSessions(recipientId
);
1158 // Retrieve profile to get the current identity key from the server
1159 profileHelper
.refreshRecipientProfile(recipientId
);
1163 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1164 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1165 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1168 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1169 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1170 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1173 private Fingerprint
computeSafetyNumberFingerprint(
1174 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1176 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1177 account
.getSelfAddress(),
1178 getIdentityKeyPair().getPublicKey(),
1183 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1184 return resolveSignalServiceAddress(resolveRecipient(address
));
1187 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1188 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1191 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1192 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1193 if (address
.getUuid().isPresent()) {
1194 return address
.toSignalServiceAddress();
1197 // Address in recipient store doesn't have a uuid, this shouldn't happen
1198 // Try to retrieve the uuid from the server
1199 final var number
= address
.getNumber().get();
1201 return resolveSignalServiceAddress(getRegisteredUser(number
));
1202 } catch (IOException e
) {
1203 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1204 // Return SignalServiceAddress with unknown UUID
1205 return address
.toSignalServiceAddress();
1209 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1210 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1211 for (var number
: recipients
) {
1212 final var recipientId
= resolveRecipient(number
);
1213 recipientIds
.add(recipientId
);
1215 return recipientIds
;
1218 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1219 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1220 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1222 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1223 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1225 return getRegisteredUser(number
);
1226 } catch (IOException e
) {
1233 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1234 return account
.getRecipientStore().resolveRecipient(address
);
1237 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1238 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1242 public void close() throws IOException
{
1246 private void close(boolean closeAccount
) throws IOException
{
1247 executor
.shutdown();
1249 dependencies
.getSignalWebSocket().disconnect();
1251 if (closeAccount
&& account
!= null) {
1257 public interface ReceiveMessageHandler
{
1259 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);