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
.api
.Device
;
20 import org
.asamk
.signal
.manager
.api
.TypingAction
;
21 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
22 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
23 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
24 import org
.asamk
.signal
.manager
.groups
.GroupId
;
25 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
26 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
27 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
28 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
29 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
30 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
31 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
32 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
33 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
34 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
35 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
36 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
37 import org
.asamk
.signal
.manager
.jobs
.Context
;
38 import org
.asamk
.signal
.manager
.jobs
.Job
;
39 import org
.asamk
.signal
.manager
.jobs
.RetrieveStickerPackJob
;
40 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
41 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
42 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
43 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
44 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
45 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
46 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
47 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
48 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
49 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
50 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
51 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
52 import org
.asamk
.signal
.manager
.util
.IOUtils
;
53 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
54 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
55 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
56 import org
.asamk
.signal
.manager
.util
.Utils
;
57 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
58 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
59 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
60 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
61 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
62 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
63 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
64 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
65 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
66 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
67 import org
.signal
.libsignal
.metadata
.SelfSendException
;
68 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
69 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
70 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
71 import org
.signal
.zkgroup
.InvalidInputException
;
72 import org
.signal
.zkgroup
.VerificationFailedException
;
73 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
74 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
75 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
76 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
77 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
78 import org
.slf4j
.Logger
;
79 import org
.slf4j
.LoggerFactory
;
80 import org
.whispersystems
.libsignal
.IdentityKey
;
81 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
82 import org
.whispersystems
.libsignal
.InvalidKeyException
;
83 import org
.whispersystems
.libsignal
.InvalidMessageException
;
84 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
85 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
86 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
87 import org
.whispersystems
.libsignal
.util
.Pair
;
88 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
89 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
90 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
91 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
92 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
93 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
94 import org
.whispersystems
.signalservice
.api
.crypto
.ContentHint
;
95 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
96 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
97 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
98 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
99 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
100 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
101 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
102 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
103 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
104 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
105 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
106 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
107 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
108 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
109 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
110 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
111 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
112 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
113 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
116 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
117 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
118 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
119 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
120 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
121 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
122 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
123 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
124 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
125 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
126 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
127 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
128 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
129 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
130 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.ConflictException
;
131 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
132 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
133 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
134 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
135 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
136 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
137 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
138 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
139 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
140 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
141 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
142 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
143 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
144 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
145 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
146 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
148 import java
.io
.Closeable
;
150 import java
.io
.FileInputStream
;
151 import java
.io
.FileOutputStream
;
152 import java
.io
.IOException
;
153 import java
.io
.InputStream
;
154 import java
.io
.OutputStream
;
156 import java
.net
.URISyntaxException
;
157 import java
.net
.URLEncoder
;
158 import java
.nio
.charset
.StandardCharsets
;
159 import java
.nio
.file
.Files
;
160 import java
.security
.SignatureException
;
161 import java
.util
.ArrayList
;
162 import java
.util
.Arrays
;
163 import java
.util
.Base64
;
164 import java
.util
.Collection
;
165 import java
.util
.Date
;
166 import java
.util
.HashSet
;
167 import java
.util
.List
;
168 import java
.util
.Map
;
169 import java
.util
.Set
;
170 import java
.util
.UUID
;
171 import java
.util
.concurrent
.ExecutorService
;
172 import java
.util
.concurrent
.Executors
;
173 import java
.util
.concurrent
.TimeUnit
;
174 import java
.util
.concurrent
.TimeoutException
;
175 import java
.util
.concurrent
.locks
.ReentrantLock
;
176 import java
.util
.function
.Function
;
177 import java
.util
.stream
.Collectors
;
179 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
181 public class Manager
implements Closeable
{
183 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
185 private final CertificateValidator certificateValidator
;
187 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
188 private final String userAgent
;
190 private SignalAccount account
;
191 private final SignalServiceAccountManager accountManager
;
192 private final GroupsV2Api groupsV2Api
;
193 private final GroupsV2Operations groupsV2Operations
;
194 private final SignalServiceMessageReceiver messageReceiver
;
195 private final ClientZkProfileOperations clientZkProfileOperations
;
197 private final ExecutorService executor
= Executors
.newCachedThreadPool();
199 private SignalServiceMessagePipe messagePipe
= null;
200 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
202 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
203 private final ProfileHelper profileHelper
;
204 private final GroupV2Helper groupV2Helper
;
205 private final PinHelper pinHelper
;
206 private final AvatarStore avatarStore
;
207 private final AttachmentStore attachmentStore
;
208 private final StickerPackStore stickerPackStore
;
209 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
210 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
213 public Lock
acquire() {
215 return LEGACY_LOCK
::unlock
;
220 SignalAccount account
,
221 PathConfig pathConfig
,
222 ServiceEnvironmentConfig serviceEnvironmentConfig
,
225 this.account
= account
;
226 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
227 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
228 this.userAgent
= userAgent
;
229 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
230 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
231 final SleepTimer timer
= new UptimeSleepTimer();
232 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
233 new DynamicCredentialsProvider(account
.getUuid(),
234 account
.getUsername(),
235 account
.getPassword(),
236 account
.getDeviceId()),
239 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
241 this.groupsV2Api
= accountManager
.getGroupsV2Api();
242 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
243 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
244 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
245 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
248 this.pinHelper
= new PinHelper(keyBackupService
);
249 this.clientZkProfileOperations
= capabilities
.isGv2()
250 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
251 .getProfileOperations()
253 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
255 account
.getUsername(),
256 account
.getPassword(),
257 account
.getDeviceId(),
261 clientZkProfileOperations
,
262 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
264 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
265 account
.getProfileStore()::getProfileKey
,
266 this::getRecipientProfile
,
267 this::getSenderCertificate
);
268 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
269 unidentifiedAccessHelper
::getAccessFor
,
270 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
271 () -> messageReceiver
,
272 this::resolveSignalServiceAddress
);
273 this.groupV2Helper
= new GroupV2Helper(this::getRecipientProfileKeyCredential
,
274 this::getRecipientProfile
,
275 account
::getSelfRecipientId
,
278 this::getGroupAuthForToday
,
279 this::resolveSignalServiceAddress
);
280 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
281 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
282 this.stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
285 public String
getUsername() {
286 return account
.getUsername();
289 public SignalServiceAddress
getSelfAddress() {
290 return account
.getSelfAddress();
293 public RecipientId
getSelfRecipientId() {
294 return account
.getSelfRecipientId();
297 private IdentityKeyPair
getIdentityKeyPair() {
298 return account
.getIdentityKeyPair();
301 public int getDeviceId() {
302 return account
.getDeviceId();
305 public static Manager
init(
306 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
307 ) throws IOException
, NotRegisteredException
{
308 var pathConfig
= PathConfig
.createDefault(settingsPath
);
310 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
311 throw new NotRegisteredException();
314 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true);
316 if (!account
.isRegistered()) {
317 throw new NotRegisteredException();
320 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
322 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
325 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
326 var pathConfig
= PathConfig
.createDefault(settingsPath
);
327 final var dataPath
= pathConfig
.getDataPath();
328 final var files
= dataPath
.listFiles();
334 return Arrays
.stream(files
)
335 .filter(File
::isFile
)
337 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
338 .collect(Collectors
.toList());
341 public void checkAccountState() throws IOException
{
342 if (account
.getLastReceiveTimestamp() == 0) {
343 logger
.warn("The Signal protocol expects that incoming messages are regularly received.");
345 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
346 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
349 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
353 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
356 if (account
.getUuid() == null) {
357 account
.setUuid(accountManager
.getOwnUuid());
359 updateAccountAttributes();
363 * This is used for checking a set of phone numbers for registration on Signal
365 * @param numbers The set of phone number in question
366 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
367 * @throws IOException if its unable to get the contacts to check if they're registered
369 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
370 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
371 var contactDetails
= getRegisteredUsers(numbers
);
373 var registeredUsers
= contactDetails
.keySet();
375 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
378 public void updateAccountAttributes() throws IOException
{
379 accountManager
.setAccountAttributes(account
.getEncryptedDeviceName(),
381 account
.getLocalRegistrationId(),
383 // set legacy pin only if no KBS master key is set
384 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
385 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
386 account
.getSelfUnidentifiedAccessKey(),
387 account
.isUnrestrictedUnidentifiedAccess(),
389 account
.isDiscoverableByPhoneNumber());
393 * @param givenName if null, the previous givenName will be kept
394 * @param familyName if null, the previous familyName will be kept
395 * @param about if null, the previous about text will be kept
396 * @param aboutEmoji if null, the previous about emoji will be kept
397 * @param avatar if avatar is null the image from the local avatar store is used (if present),
399 public void setProfile(
400 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
401 ) throws IOException
{
402 var profile
= getRecipientProfile(account
.getSelfRecipientId());
403 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
404 if (givenName
!= null) {
405 builder
.withGivenName(givenName
);
407 if (familyName
!= null) {
408 builder
.withFamilyName(familyName
);
411 builder
.withAbout(about
);
413 if (aboutEmoji
!= null) {
414 builder
.withAboutEmoji(aboutEmoji
);
416 var newProfile
= builder
.build();
418 try (final var streamDetails
= avatar
== null
419 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
420 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
421 accountManager
.setVersionedProfile(account
.getUuid(),
422 account
.getProfileKey(),
423 newProfile
.getInternalServiceName(),
424 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
425 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
430 if (avatar
!= null) {
431 if (avatar
.isPresent()) {
432 avatarStore
.storeProfileAvatar(getSelfAddress(),
433 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
435 avatarStore
.deleteProfileAvatar(getSelfAddress());
438 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
441 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
442 } catch (UntrustedIdentityException ignored
) {
446 public void unregister() throws IOException
{
447 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
448 // If this is the master device, other users can't send messages to this number anymore.
449 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
450 accountManager
.setGcmId(Optional
.absent());
452 account
.setRegistered(false);
455 public void deleteAccount() throws IOException
{
456 accountManager
.deleteAccount();
458 account
.setRegistered(false);
461 public List
<Device
> getLinkedDevices() throws IOException
{
462 var devices
= accountManager
.getDevices();
463 account
.setMultiDevice(devices
.size() > 1);
464 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
465 return devices
.stream().map(d
-> {
466 String deviceName
= d
.getName();
467 if (deviceName
!= null) {
469 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
470 } catch (IOException e
) {
471 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
474 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
475 }).collect(Collectors
.toList());
478 public void removeLinkedDevices(int deviceId
) throws IOException
{
479 accountManager
.removeDevice(deviceId
);
480 var devices
= accountManager
.getDevices();
481 account
.setMultiDevice(devices
.size() > 1);
484 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
485 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
487 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
490 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
491 var identityKeyPair
= getIdentityKeyPair();
492 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
494 accountManager
.addDevice(deviceIdentifier
,
497 Optional
.of(account
.getProfileKey().serialize()),
499 account
.setMultiDevice(true);
502 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
503 if (!account
.isMasterDevice()) {
504 throw new RuntimeException("Only master device can set a PIN");
506 if (pin
.isPresent()) {
507 final var masterKey
= account
.getPinMasterKey() != null
508 ? account
.getPinMasterKey()
509 : KeyUtils
.createMasterKey();
511 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
513 account
.setRegistrationLockPin(pin
.get(), masterKey
);
515 // Remove legacy registration lock
516 accountManager
.removeRegistrationLockV1();
519 pinHelper
.removeRegistrationLockPin();
521 account
.setRegistrationLockPin(null, null);
525 void refreshPreKeys() throws IOException
{
526 var oneTimePreKeys
= generatePreKeys();
527 final var identityKeyPair
= getIdentityKeyPair();
528 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
530 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
533 private List
<PreKeyRecord
> generatePreKeys() {
534 final var offset
= account
.getPreKeyIdOffset();
536 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
537 account
.addPreKeys(records
);
542 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
543 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
545 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
546 account
.addSignedPreKey(record);
551 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
552 if (messagePipe
== null) {
553 messagePipe
= messageReceiver
.createMessagePipe();
558 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
559 if (unidentifiedMessagePipe
== null) {
560 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
562 return unidentifiedMessagePipe
;
565 private SignalServiceMessageSender
createMessageSender() {
566 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
568 account
.getUsername(),
569 account
.getPassword(),
570 account
.getDeviceId(),
571 account
.getSignalProtocolStore(),
574 account
.isMultiDevice(),
575 Optional
.fromNullable(messagePipe
),
576 Optional
.fromNullable(unidentifiedMessagePipe
),
578 clientZkProfileOperations
,
580 ServiceConfig
.MAX_ENVELOPE_SIZE
,
581 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
584 public Profile
getRecipientProfile(
585 RecipientId recipientId
587 return getRecipientProfile(recipientId
, false);
590 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
592 Profile
getRecipientProfile(
593 RecipientId recipientId
, boolean force
595 var profile
= account
.getProfileStore().getProfile(recipientId
);
597 var now
= System
.currentTimeMillis();
598 // Profiles are cached for 24h before retrieving them again, unless forced
599 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
603 synchronized (pendingProfileRequest
) {
604 if (pendingProfileRequest
.contains(recipientId
)) {
607 pendingProfileRequest
.add(recipientId
);
609 final SignalServiceProfile encryptedProfile
;
611 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
613 synchronized (pendingProfileRequest
) {
614 pendingProfileRequest
.remove(recipientId
);
617 if (encryptedProfile
== null) {
621 profile
= decryptProfileIfKeyKnown(recipientId
, encryptedProfile
);
622 account
.getProfileStore().storeProfile(recipientId
, profile
);
627 private Profile
decryptProfileIfKeyKnown(
628 final RecipientId recipientId
, final SignalServiceProfile encryptedProfile
630 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
631 if (profileKey
== null) {
632 return new Profile(System
.currentTimeMillis(),
637 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
638 ProfileUtils
.getCapabilities(encryptedProfile
));
641 return decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
644 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
646 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
647 } catch (IOException e
) {
648 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
653 private ProfileAndCredential
retrieveProfileAndCredential(
654 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
655 ) throws IOException
{
656 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
657 final var profile
= profileAndCredential
.getProfile();
660 var newIdentity
= account
.getIdentityKeyStore()
661 .saveIdentity(recipientId
,
662 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
666 account
.getSessionStore().archiveSessions(recipientId
);
668 } catch (InvalidKeyException ignored
) {
669 logger
.warn("Got invalid identity key in profile for {}",
670 resolveSignalServiceAddress(recipientId
).getIdentifier());
672 return profileAndCredential
;
675 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
676 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
677 if (profileKeyCredential
!= null) {
678 return profileKeyCredential
;
681 ProfileAndCredential profileAndCredential
;
683 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
684 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
685 } catch (IOException e
) {
686 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
690 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
691 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
693 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
694 if (profileKey
!= null) {
695 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
697 profileAndCredential
.getProfile());
698 account
.getProfileStore().storeProfile(recipientId
, profile
);
701 return profileKeyCredential
;
704 private Profile
decryptProfileAndDownloadAvatar(
705 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
707 if (encryptedProfile
.getAvatar() != null) {
708 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
711 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
714 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
715 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
716 if (streamDetails
== null) {
717 return Optional
.absent();
720 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
723 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
724 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
725 if (streamDetails
== null) {
726 return Optional
.absent();
729 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
732 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
733 var g
= getGroup(groupId
);
735 throw new GroupNotFoundException(groupId
);
737 if (!g
.isMember(account
.getSelfRecipientId())) {
738 throw new NotAGroupMemberException(groupId
, g
.getTitle());
743 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
744 var g
= getGroup(groupId
);
746 throw new GroupNotFoundException(groupId
);
748 if (!g
.isMember(account
.getSelfRecipientId()) && !g
.isPendingMember(account
.getSelfRecipientId())) {
749 throw new NotAGroupMemberException(groupId
, g
.getTitle());
754 public List
<GroupInfo
> getGroups() {
755 return account
.getGroupStore().getGroups();
758 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
759 String messageText
, List
<String
> attachments
, GroupId groupId
760 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
761 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
762 if (attachments
!= null) {
763 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
766 return sendGroupMessage(messageBuilder
, groupId
);
769 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
770 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
771 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
772 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
773 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
775 resolveSignalServiceAddress(targetAuthorRecipientId
),
776 targetSentTimestamp
);
777 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
779 return sendGroupMessage(messageBuilder
, groupId
);
782 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
783 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
784 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
785 final var g
= getGroupForSending(groupId
);
787 GroupUtils
.setGroupContext(messageBuilder
, g
);
788 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
790 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfRecipientId()));
793 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(
794 GroupId groupId
, Set
<String
> groupAdmins
795 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, InvalidNumberException
, LastGroupAdminException
{
796 var group
= getGroupForUpdating(groupId
);
797 if (group
instanceof GroupInfoV1
) {
798 return quitGroupV1((GroupInfoV1
) group
);
801 final var newAdmins
= getSignalServiceAddresses(groupAdmins
);
803 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
804 } catch (ConflictException e
) {
805 // Detected conflicting update, refreshing group and trying again
806 group
= getGroup(groupId
, true);
807 return quitGroupV2((GroupInfoV2
) group
, newAdmins
);
811 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV1(final GroupInfoV1 groupInfoV1
) throws IOException
{
812 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
813 .withId(groupInfoV1
.getGroupId().serialize())
816 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
817 groupInfoV1
.removeMember(account
.getSelfRecipientId());
818 account
.getGroupStore().updateGroup(groupInfoV1
);
819 return sendMessage(messageBuilder
, groupInfoV1
.getMembersWithout(account
.getSelfRecipientId()));
822 private Pair
<Long
, List
<SendMessageResult
>> quitGroupV2(
823 final GroupInfoV2 groupInfoV2
, final Set
<RecipientId
> newAdmins
824 ) throws LastGroupAdminException
, IOException
{
825 final var currentAdmins
= groupInfoV2
.getAdminMembers();
826 newAdmins
.removeAll(currentAdmins
);
827 newAdmins
.retainAll(groupInfoV2
.getMembers());
828 if (currentAdmins
.contains(getSelfRecipientId())
829 && currentAdmins
.size() == 1
830 && groupInfoV2
.getMembers().size() > 1
831 && newAdmins
.size() == 0) {
832 // Last admin can't leave the group, unless she's also the last member
833 throw new LastGroupAdminException(groupInfoV2
.getGroupId(), groupInfoV2
.getTitle());
835 final var groupGroupChangePair
= groupV2Helper
.leaveGroup(groupInfoV2
, newAdmins
);
836 groupInfoV2
.setGroup(groupGroupChangePair
.first(), this::resolveRecipient
);
837 var messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
838 account
.getGroupStore().updateGroup(groupInfoV2
);
839 return sendMessage(messageBuilder
, groupInfoV2
.getMembersWithout(account
.getSelfRecipientId()));
842 public void deleteGroup(GroupId groupId
) throws IOException
{
843 account
.getGroupStore().deleteGroup(groupId
);
844 avatarStore
.deleteGroupAvatar(groupId
);
847 public Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
848 String name
, List
<String
> members
, File avatarFile
849 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
850 return createGroup(name
, members
== null ?
null : getSignalServiceAddresses(members
), avatarFile
);
853 private Pair
<GroupId
, List
<SendMessageResult
>> createGroup(
854 String name
, Set
<RecipientId
> members
, File avatarFile
855 ) throws IOException
, AttachmentInvalidException
{
856 final var selfRecipientId
= account
.getSelfRecipientId();
857 if (members
!= null && members
.contains(selfRecipientId
)) {
858 members
= new HashSet
<>(members
);
859 members
.remove(selfRecipientId
);
862 var gv2Pair
= groupV2Helper
.createGroup(name
== null ?
"" : name
,
863 members
== null ? Set
.of() : members
,
866 SignalServiceDataMessage
.Builder messageBuilder
;
867 if (gv2Pair
== null) {
868 // Failed to create v2 group, creating v1 group instead
869 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
870 gv1
.addMembers(List
.of(selfRecipientId
));
871 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
872 return new Pair
<>(gv1
.getGroupId(), result
.second());
875 final var gv2
= gv2Pair
.first();
876 final var decryptedGroup
= gv2Pair
.second();
878 gv2
.setGroup(decryptedGroup
, this::resolveRecipient
);
879 if (avatarFile
!= null) {
880 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
881 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
883 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
884 account
.getGroupStore().updateGroup(gv2
);
886 final var result
= sendMessage(messageBuilder
, gv2
.getMembersIncludingPendingWithout(selfRecipientId
));
887 return new Pair
<>(gv2
.getGroupId(), result
.second());
890 public Pair
<Long
, List
<SendMessageResult
>> updateGroup(
894 List
<String
> members
,
895 List
<String
> removeMembers
,
897 List
<String
> removeAdmins
,
898 boolean resetGroupLink
,
899 GroupLinkState groupLinkState
,
900 GroupPermission addMemberPermission
,
901 GroupPermission editDetailsPermission
,
903 Integer expirationTimer
904 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
905 return updateGroup(groupId
,
908 members
== null ?
null : getSignalServiceAddresses(members
),
909 removeMembers
== null ?
null : getSignalServiceAddresses(removeMembers
),
910 admins
== null ?
null : getSignalServiceAddresses(admins
),
911 removeAdmins
== null ?
null : getSignalServiceAddresses(removeAdmins
),
915 editDetailsPermission
,
920 private Pair
<Long
, List
<SendMessageResult
>> updateGroup(
921 final GroupId groupId
,
923 final String description
,
924 final Set
<RecipientId
> members
,
925 final Set
<RecipientId
> removeMembers
,
926 final Set
<RecipientId
> admins
,
927 final Set
<RecipientId
> removeAdmins
,
928 final boolean resetGroupLink
,
929 final GroupLinkState groupLinkState
,
930 final GroupPermission addMemberPermission
,
931 final GroupPermission editDetailsPermission
,
932 final File avatarFile
,
933 final Integer expirationTimer
934 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
935 var group
= getGroupForUpdating(groupId
);
937 if (group
instanceof GroupInfoV2
) {
939 return updateGroupV2((GroupInfoV2
) group
,
949 editDetailsPermission
,
952 } catch (ConflictException e
) {
953 // Detected conflicting update, refreshing group and trying again
954 group
= getGroup(groupId
, true);
955 return updateGroupV2((GroupInfoV2
) group
,
965 editDetailsPermission
,
971 final var gv1
= (GroupInfoV1
) group
;
972 final var result
= updateGroupV1(gv1
, name
, members
, avatarFile
);
973 if (expirationTimer
!= null) {
974 setExpirationTimer(gv1
, expirationTimer
);
979 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV1(
980 final GroupInfoV1 gv1
, final String name
, final Set
<RecipientId
> members
, final File avatarFile
981 ) throws IOException
, AttachmentInvalidException
{
982 updateGroupV1Details(gv1
, name
, members
, avatarFile
);
983 var messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
985 account
.getGroupStore().updateGroup(gv1
);
987 return sendMessage(messageBuilder
, gv1
.getMembersIncludingPendingWithout(account
.getSelfRecipientId()));
990 private void updateGroupV1Details(
991 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
992 ) throws IOException
{
997 if (members
!= null) {
998 final var newMemberAddresses
= members
.stream()
999 .filter(member
-> !g
.isMember(member
))
1000 .map(this::resolveSignalServiceAddress
)
1001 .collect(Collectors
.toList());
1002 final var newE164Members
= new HashSet
<String
>();
1003 for (var member
: newMemberAddresses
) {
1004 if (!member
.getNumber().isPresent()) {
1007 newE164Members
.add(member
.getNumber().get());
1010 final var registeredUsers
= getRegisteredUsers(newE164Members
);
1011 if (registeredUsers
.size() != newE164Members
.size()) {
1012 // Some of the new members are not registered on Signal
1013 newE164Members
.removeAll(registeredUsers
.keySet());
1014 throw new IOException("Failed to add members "
1015 + String
.join(", ", newE164Members
)
1016 + " to group: Not registered on Signal");
1019 g
.addMembers(members
);
1022 if (avatarFile
!= null) {
1023 avatarStore
.storeGroupAvatar(g
.getGroupId(),
1024 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1028 private Pair
<Long
, List
<SendMessageResult
>> updateGroupV2(
1029 final GroupInfoV2 group
,
1031 final String description
,
1032 final Set
<RecipientId
> members
,
1033 final Set
<RecipientId
> removeMembers
,
1034 final Set
<RecipientId
> admins
,
1035 final Set
<RecipientId
> removeAdmins
,
1036 final boolean resetGroupLink
,
1037 final GroupLinkState groupLinkState
,
1038 final GroupPermission addMemberPermission
,
1039 final GroupPermission editDetailsPermission
,
1040 final File avatarFile
,
1041 Integer expirationTimer
1042 ) throws IOException
{
1043 Pair
<Long
, List
<SendMessageResult
>> result
= null;
1044 if (group
.isPendingMember(account
.getSelfRecipientId())) {
1045 var groupGroupChangePair
= groupV2Helper
.acceptInvite(group
);
1046 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1049 if (members
!= null) {
1050 final var newMembers
= new HashSet
<>(members
);
1051 newMembers
.removeAll(group
.getMembers());
1052 if (newMembers
.size() > 0) {
1053 var groupGroupChangePair
= groupV2Helper
.addMembers(group
, newMembers
);
1054 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1058 if (removeMembers
!= null) {
1059 var existingRemoveMembers
= new HashSet
<>(removeMembers
);
1060 existingRemoveMembers
.retainAll(group
.getMembers());
1061 existingRemoveMembers
.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
1062 if (existingRemoveMembers
.size() > 0) {
1063 var groupGroupChangePair
= groupV2Helper
.removeMembers(group
, existingRemoveMembers
);
1064 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1067 var pendingRemoveMembers
= new HashSet
<>(removeMembers
);
1068 pendingRemoveMembers
.retainAll(group
.getPendingMembers());
1069 if (pendingRemoveMembers
.size() > 0) {
1070 var groupGroupChangePair
= groupV2Helper
.revokeInvitedMembers(group
, pendingRemoveMembers
);
1071 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1075 if (admins
!= null) {
1076 final var newAdmins
= new HashSet
<>(admins
);
1077 newAdmins
.retainAll(group
.getMembers());
1078 newAdmins
.removeAll(group
.getAdminMembers());
1079 if (newAdmins
.size() > 0) {
1080 for (var admin
: newAdmins
) {
1081 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, true);
1082 result
= sendUpdateGroupV2Message(group
,
1083 groupGroupChangePair
.first(),
1084 groupGroupChangePair
.second());
1089 if (removeAdmins
!= null) {
1090 final var existingRemoveAdmins
= new HashSet
<>(removeAdmins
);
1091 existingRemoveAdmins
.retainAll(group
.getAdminMembers());
1092 if (existingRemoveAdmins
.size() > 0) {
1093 for (var admin
: existingRemoveAdmins
) {
1094 var groupGroupChangePair
= groupV2Helper
.setMemberAdmin(group
, admin
, false);
1095 result
= sendUpdateGroupV2Message(group
,
1096 groupGroupChangePair
.first(),
1097 groupGroupChangePair
.second());
1102 if (resetGroupLink
) {
1103 var groupGroupChangePair
= groupV2Helper
.resetGroupLinkPassword(group
);
1104 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1107 if (groupLinkState
!= null) {
1108 var groupGroupChangePair
= groupV2Helper
.setGroupLinkState(group
, groupLinkState
);
1109 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1112 if (addMemberPermission
!= null) {
1113 var groupGroupChangePair
= groupV2Helper
.setAddMemberPermission(group
, addMemberPermission
);
1114 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1117 if (editDetailsPermission
!= null) {
1118 var groupGroupChangePair
= groupV2Helper
.setEditDetailsPermission(group
, editDetailsPermission
);
1119 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1122 if (expirationTimer
!= null) {
1123 var groupGroupChangePair
= groupV2Helper
.setMessageExpirationTimer(group
, expirationTimer
);
1124 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1127 if (name
!= null || description
!= null || avatarFile
!= null) {
1128 var groupGroupChangePair
= groupV2Helper
.updateGroup(group
, name
, description
, avatarFile
);
1129 if (avatarFile
!= null) {
1130 avatarStore
.storeGroupAvatar(group
.getGroupId(),
1131 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
1133 result
= sendUpdateGroupV2Message(group
, groupGroupChangePair
.first(), groupGroupChangePair
.second());
1139 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
1140 GroupInviteLinkUrl inviteLinkUrl
1141 ) throws IOException
, GroupLinkNotActiveException
{
1142 final var groupJoinInfo
= groupV2Helper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
1143 inviteLinkUrl
.getPassword());
1144 final var groupChange
= groupV2Helper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
1145 inviteLinkUrl
.getPassword(),
1147 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
1148 groupJoinInfo
.getRevision() + 1,
1149 groupChange
.toByteArray());
1151 if (group
.getGroup() == null) {
1152 // Only requested member, can't send update to group members
1153 return new Pair
<>(group
.getGroupId(), List
.of());
1156 final var result
= sendUpdateGroupV2Message(group
, group
.getGroup(), groupChange
);
1158 return new Pair
<>(group
.getGroupId(), result
.second());
1161 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupV2Message(
1162 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
1163 ) throws IOException
{
1164 final var selfRecipientId
= account
.getSelfRecipientId();
1165 final var members
= group
.getMembersIncludingPendingWithout(selfRecipientId
);
1166 group
.setGroup(newDecryptedGroup
, this::resolveRecipient
);
1167 members
.addAll(group
.getMembersIncludingPendingWithout(selfRecipientId
));
1169 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
1170 account
.getGroupStore().updateGroup(group
);
1171 return sendMessage(messageBuilder
, members
);
1174 private static int currentTimeDays() {
1175 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
1178 private GroupsV2AuthorizationString
getGroupAuthForToday(
1179 final GroupSecretParams groupSecretParams
1180 ) throws IOException
{
1181 final var today
= currentTimeDays();
1182 // Returns credentials for the next 7 days
1183 final var credentials
= groupsV2Api
.getCredentials(today
);
1184 // TODO cache credentials until they expire
1185 var authCredentialResponse
= credentials
.get(today
);
1187 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
1190 authCredentialResponse
);
1191 } catch (VerificationFailedException e
) {
1192 throw new IOException(e
);
1196 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
1197 GroupIdV1 groupId
, SignalServiceAddress recipient
1198 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
1200 var group
= getGroupForSending(groupId
);
1201 if (!(group
instanceof GroupInfoV1
)) {
1202 throw new RuntimeException("Received an invalid group request for a v2 group!");
1204 g
= (GroupInfoV1
) group
;
1206 final var recipientId
= resolveRecipient(recipient
);
1207 if (!g
.isMember(recipientId
)) {
1208 throw new NotAGroupMemberException(groupId
, g
.name
);
1211 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
1213 // Send group message only to the recipient who requested it
1214 return sendMessage(messageBuilder
, Set
.of(recipientId
));
1217 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
1218 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
1219 .withId(g
.getGroupId().serialize())
1221 .withMembers(g
.getMembers()
1223 .map(this::resolveSignalServiceAddress
)
1224 .collect(Collectors
.toList()));
1227 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
1228 if (attachment
.isPresent()) {
1229 group
.withAvatar(attachment
.get());
1231 } catch (IOException e
) {
1232 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
1235 return SignalServiceDataMessage
.newBuilder()
1236 .asGroupMessage(group
.build())
1237 .withExpiration(g
.getMessageExpirationTime());
1240 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
1241 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
1242 .withRevision(g
.getGroup().getRevision())
1243 .withSignedGroupChange(signedGroupChange
);
1244 return SignalServiceDataMessage
.newBuilder()
1245 .asGroupMessage(group
.build())
1246 .withExpiration(g
.getMessageExpirationTime());
1249 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
1250 GroupIdV1 groupId
, SignalServiceAddress recipient
1251 ) throws IOException
{
1252 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
1254 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
1256 // Send group info request message to the recipient who sent us a message with this groupId
1257 return sendMessage(messageBuilder
, Set
.of(resolveRecipient(recipient
)));
1261 SignalServiceAddress remoteAddress
, long messageId
1262 ) throws IOException
, UntrustedIdentityException
{
1263 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1265 System
.currentTimeMillis());
1267 createMessageSender().sendReceipt(remoteAddress
,
1268 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1272 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1273 String messageText
, List
<String
> attachments
, List
<String
> recipients
1274 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1275 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1276 if (attachments
!= null) {
1277 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1279 // Upload attachments here, so we only upload once even for multiple recipients
1280 var messageSender
= createMessageSender();
1281 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1282 for (var attachment
: attachmentStreams
) {
1283 if (attachment
.isStream()) {
1284 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1285 } else if (attachment
.isPointer()) {
1286 attachmentPointers
.add(attachment
.asPointer());
1290 messageBuilder
.withAttachments(attachmentPointers
);
1292 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1295 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1296 String messageText
, List
<String
> attachments
1297 ) throws IOException
, AttachmentInvalidException
{
1298 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1299 if (attachments
!= null) {
1300 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1302 return sendSelfMessage(messageBuilder
);
1305 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1306 long targetSentTimestamp
, List
<String
> recipients
1307 ) throws IOException
, InvalidNumberException
{
1308 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1309 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1310 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1313 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1314 long targetSentTimestamp
, GroupId groupId
1315 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1316 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1317 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1318 return sendGroupMessage(messageBuilder
, groupId
);
1321 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1322 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1323 ) throws IOException
, InvalidNumberException
{
1324 var targetAuthorRecipientId
= canonicalizeAndResolveRecipient(targetAuthor
);
1325 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1327 resolveSignalServiceAddress(targetAuthorRecipientId
),
1328 targetSentTimestamp
);
1329 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1330 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1333 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1334 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1336 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1338 return sendMessage(messageBuilder
, signalServiceAddresses
);
1339 } catch (Exception e
) {
1340 for (var address
: signalServiceAddresses
) {
1341 handleEndSession(address
);
1347 void renewSession(RecipientId recipientId
) throws IOException
{
1348 account
.getSessionStore().archiveSessions(recipientId
);
1349 if (!recipientId
.equals(getSelfRecipientId())) {
1350 sendNullMessage(recipientId
);
1354 public String
getContactName(String number
) throws InvalidNumberException
{
1355 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1356 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1359 public void setContactName(String number
, String name
) throws InvalidNumberException
, NotMasterDeviceException
{
1360 if (!account
.isMasterDevice()) {
1361 throw new NotMasterDeviceException();
1363 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1364 var contact
= account
.getContactStore().getContact(recipientId
);
1365 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1366 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1369 public void setContactBlocked(
1370 String number
, boolean blocked
1371 ) throws InvalidNumberException
, NotMasterDeviceException
{
1372 if (!account
.isMasterDevice()) {
1373 throw new NotMasterDeviceException();
1375 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1378 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1379 var contact
= account
.getContactStore().getContact(recipientId
);
1380 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1381 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1384 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1385 var group
= getGroup(groupId
);
1386 if (group
== null) {
1387 throw new GroupNotFoundException(groupId
);
1390 group
.setBlocked(blocked
);
1391 account
.getGroupStore().updateGroup(group
);
1394 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1395 var contact
= account
.getContactStore().getContact(recipientId
);
1396 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1399 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1400 account
.getContactStore()
1401 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1404 private void sendExpirationTimerUpdate(RecipientId recipientId
) throws IOException
{
1405 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1406 sendMessage(messageBuilder
, Set
.of(recipientId
));
1410 * Change the expiration timer for a contact
1412 public void setExpirationTimer(
1413 String number
, int messageExpirationTimer
1414 ) throws IOException
, InvalidNumberException
{
1415 var recipientId
= canonicalizeAndResolveRecipient(number
);
1416 setExpirationTimer(recipientId
, messageExpirationTimer
);
1417 sendExpirationTimerUpdate(recipientId
);
1421 * Change the expiration timer for a group
1423 private void setExpirationTimer(
1424 GroupInfoV1 groupInfoV1
, int messageExpirationTimer
1425 ) throws NotAGroupMemberException
, GroupNotFoundException
, IOException
{
1426 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1427 account
.getGroupStore().updateGroup(groupInfoV1
);
1428 sendExpirationTimerUpdate(groupInfoV1
.getGroupId());
1431 private void sendExpirationTimerUpdate(GroupIdV1 groupId
) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1432 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1433 sendGroupMessage(messageBuilder
, groupId
);
1437 * Upload the sticker pack from path.
1439 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1440 * @return if successful, returns the URL to install the sticker pack in the signal app
1442 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1443 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1445 var messageSender
= createMessageSender();
1447 var packKey
= KeyUtils
.createStickerUploadKey();
1448 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1449 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
1451 var sticker
= new Sticker(packId
, packKey
);
1452 account
.getStickerStore().updateSticker(sticker
);
1455 return new URI("https",
1459 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
1461 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
)).toString();
1462 } catch (URISyntaxException e
) {
1463 throw new AssertionError(e
);
1467 public void requestAllSyncData() throws IOException
{
1468 requestSyncGroups();
1469 requestSyncContacts();
1470 requestSyncBlocked();
1471 requestSyncConfiguration();
1475 private void requestSyncGroups() throws IOException
{
1476 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1477 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1479 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1481 sendSyncMessage(message
);
1482 } catch (UntrustedIdentityException e
) {
1483 throw new AssertionError(e
);
1487 private void requestSyncContacts() throws IOException
{
1488 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1489 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1491 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1493 sendSyncMessage(message
);
1494 } catch (UntrustedIdentityException e
) {
1495 throw new AssertionError(e
);
1499 private void requestSyncBlocked() throws IOException
{
1500 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1501 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1503 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1505 sendSyncMessage(message
);
1506 } catch (UntrustedIdentityException e
) {
1507 throw new AssertionError(e
);
1511 private void requestSyncConfiguration() throws IOException
{
1512 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1513 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1515 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1517 sendSyncMessage(message
);
1518 } catch (UntrustedIdentityException e
) {
1519 throw new AssertionError(e
);
1523 private void requestSyncKeys() throws IOException
{
1524 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1525 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1527 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1529 sendSyncMessage(message
);
1530 } catch (UntrustedIdentityException e
) {
1531 throw new AssertionError(e
);
1535 private byte[] getSenderCertificate() {
1538 if (account
.isPhoneNumberShared()) {
1539 certificate
= accountManager
.getSenderCertificate();
1541 certificate
= accountManager
.getSenderCertificateForPhoneNumberPrivacy();
1543 } catch (IOException e
) {
1544 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1547 // TODO cache for a day
1551 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1552 var messageSender
= createMessageSender();
1553 messageSender
.sendSyncMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1556 private Set
<RecipientId
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1557 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1558 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1560 for (var number
: numbers
) {
1561 final var resolvedAddress
= resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number
));
1562 if (resolvedAddress
.getUuid().isPresent()) {
1563 signalServiceAddresses
.add(resolvedAddress
);
1565 addressesMissingUuid
.add(resolvedAddress
);
1569 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1570 .map(a
-> a
.getNumber().get())
1571 .collect(Collectors
.toSet());
1572 Map
<String
, UUID
> registeredUsers
;
1574 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1575 } catch (IOException e
) {
1576 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1577 registeredUsers
= Map
.of();
1580 for (var address
: addressesMissingUuid
) {
1581 final var number
= address
.getNumber().get();
1582 if (registeredUsers
.containsKey(number
)) {
1583 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1584 registeredUsers
.get(number
),
1586 signalServiceAddresses
.add(newAddress
);
1588 signalServiceAddresses
.add(address
);
1592 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1595 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
1596 final var address
= resolveSignalServiceAddress(recipientId
);
1597 if (!address
.getNumber().isPresent()) {
1600 final var number
= address
.getNumber().get();
1601 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
1602 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
1605 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
1607 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1609 serviceEnvironmentConfig
.getCdsMrenclave());
1610 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1611 throw new IOException(e
);
1615 public void sendTypingMessage(
1616 TypingAction action
, Set
<String
> recipients
1617 ) throws IOException
, UntrustedIdentityException
, InvalidNumberException
{
1618 sendTypingMessageInternal(action
, getSignalServiceAddresses(recipients
));
1621 private void sendTypingMessageInternal(
1622 TypingAction action
, Set
<RecipientId
> recipientIds
1623 ) throws IOException
, UntrustedIdentityException
{
1624 final var timestamp
= System
.currentTimeMillis();
1625 var message
= new SignalServiceTypingMessage(action
.toSignalService(), timestamp
, Optional
.absent());
1626 var messageSender
= createMessageSender();
1627 for (var recipientId
: recipientIds
) {
1628 final var address
= resolveSignalServiceAddress(recipientId
);
1629 messageSender
.sendTyping(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
), message
);
1633 public void sendGroupTypingMessage(
1634 TypingAction action
, GroupId groupId
1635 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1636 final var timestamp
= System
.currentTimeMillis();
1637 final var g
= getGroupForSending(groupId
);
1638 final var message
= new SignalServiceTypingMessage(action
.toSignalService(),
1640 Optional
.of(groupId
.serialize()));
1641 final var messageSender
= createMessageSender();
1642 final var recipientIdList
= new ArrayList
<>(g
.getMembersWithout(account
.getSelfRecipientId()));
1643 final var addresses
= recipientIdList
.stream()
1644 .map(this::resolveSignalServiceAddress
)
1645 .collect(Collectors
.toList());
1646 messageSender
.sendTyping(addresses
, unidentifiedAccessHelper
.getAccessFor(recipientIdList
), message
, null);
1649 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1650 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientId
> recipientIds
1651 ) throws IOException
{
1652 final var timestamp
= System
.currentTimeMillis();
1653 messageBuilder
.withTimestamp(timestamp
);
1654 getOrCreateMessagePipe();
1655 getOrCreateUnidentifiedMessagePipe();
1656 SignalServiceDataMessage message
= null;
1658 message
= messageBuilder
.build();
1659 if (message
.getGroupContext().isPresent()) {
1661 var messageSender
= createMessageSender();
1662 final var isRecipientUpdate
= false;
1663 final var recipientIdList
= new ArrayList
<>(recipientIds
);
1664 final var addresses
= recipientIdList
.stream()
1665 .map(this::resolveSignalServiceAddress
)
1666 .collect(Collectors
.toList());
1667 var result
= messageSender
.sendDataMessage(addresses
,
1668 unidentifiedAccessHelper
.getAccessFor(recipientIdList
),
1670 ContentHint
.DEFAULT
,
1673 for (var r
: result
) {
1674 if (r
.getIdentityFailure() != null) {
1675 final var recipientId
= resolveRecipient(r
.getAddress());
1676 final var newIdentity
= account
.getIdentityKeyStore()
1677 .saveIdentity(recipientId
, r
.getIdentityFailure().getIdentityKey(), new Date());
1679 account
.getSessionStore().archiveSessions(recipientId
);
1684 return new Pair
<>(timestamp
, result
);
1685 } catch (UntrustedIdentityException e
) {
1686 return new Pair
<>(timestamp
, List
.of());
1689 // Send to all individually, so sync messages are sent correctly
1690 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1691 var results
= new ArrayList
<SendMessageResult
>(recipientIds
.size());
1692 for (var recipientId
: recipientIds
) {
1693 final var contact
= account
.getContactStore().getContact(recipientId
);
1694 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1695 messageBuilder
.withExpiration(expirationTime
);
1696 message
= messageBuilder
.build();
1697 results
.add(sendMessage(recipientId
, message
));
1699 return new Pair
<>(timestamp
, results
);
1702 if (message
!= null && message
.isEndSession()) {
1703 for (var recipient
: recipientIds
) {
1704 handleEndSession(recipient
);
1710 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1711 SignalServiceDataMessage
.Builder messageBuilder
1712 ) throws IOException
{
1713 final var timestamp
= System
.currentTimeMillis();
1714 messageBuilder
.withTimestamp(timestamp
);
1715 getOrCreateMessagePipe();
1716 getOrCreateUnidentifiedMessagePipe();
1717 final var recipientId
= account
.getSelfRecipientId();
1719 final var contact
= account
.getContactStore().getContact(recipientId
);
1720 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1721 messageBuilder
.withExpiration(expirationTime
);
1723 var message
= messageBuilder
.build();
1724 final var result
= sendSelfMessage(message
);
1725 return new Pair
<>(timestamp
, result
);
1728 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1729 var messageSender
= createMessageSender();
1731 var recipientId
= account
.getSelfRecipientId();
1733 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipientId
);
1734 var recipient
= resolveSignalServiceAddress(recipientId
);
1735 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1736 message
.getTimestamp(),
1738 message
.getExpiresInSeconds(),
1739 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1741 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1744 var startTime
= System
.currentTimeMillis();
1745 messageSender
.sendSyncMessage(syncMessage
, unidentifiedAccess
);
1746 return SendMessageResult
.success(recipient
,
1747 unidentifiedAccess
.isPresent(),
1749 System
.currentTimeMillis() - startTime
);
1750 } catch (UntrustedIdentityException e
) {
1751 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1755 private SendMessageResult
sendMessage(
1756 RecipientId recipientId
, SignalServiceDataMessage message
1757 ) throws IOException
{
1758 var messageSender
= createMessageSender();
1760 final var address
= resolveSignalServiceAddress(recipientId
);
1763 return messageSender
.sendDataMessage(address
,
1764 unidentifiedAccessHelper
.getAccessFor(recipientId
),
1765 ContentHint
.DEFAULT
,
1767 } catch (UnregisteredUserException e
) {
1768 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1769 return messageSender
.sendDataMessage(resolveSignalServiceAddress(newRecipientId
),
1770 unidentifiedAccessHelper
.getAccessFor(newRecipientId
),
1771 ContentHint
.DEFAULT
,
1774 } catch (UntrustedIdentityException e
) {
1775 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1779 private SendMessageResult
sendNullMessage(RecipientId recipientId
) throws IOException
{
1780 var messageSender
= createMessageSender();
1782 final var address
= resolveSignalServiceAddress(recipientId
);
1785 return messageSender
.sendNullMessage(address
, unidentifiedAccessHelper
.getAccessFor(recipientId
));
1786 } catch (UnregisteredUserException e
) {
1787 final var newRecipientId
= refreshRegisteredUser(recipientId
);
1788 final var newAddress
= resolveSignalServiceAddress(newRecipientId
);
1789 return messageSender
.sendNullMessage(newAddress
, unidentifiedAccessHelper
.getAccessFor(newRecipientId
));
1791 } catch (UntrustedIdentityException e
) {
1792 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1796 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, ProtocolUntrustedIdentityException
{
1797 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1798 account
.getSignalProtocolStore(),
1800 certificateValidator
);
1801 return cipher
.decrypt(envelope
);
1804 private void handleEndSession(RecipientId recipientId
) {
1805 account
.getSessionStore().deleteAllSessions(recipientId
);
1808 private List
<HandleAction
> handleSignalServiceDataMessage(
1809 SignalServiceDataMessage message
,
1811 SignalServiceAddress source
,
1812 SignalServiceAddress destination
,
1813 boolean ignoreAttachments
1815 var actions
= new ArrayList
<HandleAction
>();
1816 if (message
.getGroupContext().isPresent()) {
1817 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1818 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1819 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1820 var group
= getGroup(groupId
);
1821 if (group
== null || group
instanceof GroupInfoV1
) {
1822 var groupV1
= (GroupInfoV1
) group
;
1823 switch (groupInfo
.getType()) {
1825 if (groupV1
== null) {
1826 groupV1
= new GroupInfoV1(groupId
);
1829 if (groupInfo
.getAvatar().isPresent()) {
1830 var avatar
= groupInfo
.getAvatar().get();
1831 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1834 if (groupInfo
.getName().isPresent()) {
1835 groupV1
.name
= groupInfo
.getName().get();
1838 if (groupInfo
.getMembers().isPresent()) {
1839 groupV1
.addMembers(groupInfo
.getMembers()
1842 .map(this::resolveRecipient
)
1843 .collect(Collectors
.toSet()));
1846 account
.getGroupStore().updateGroup(groupV1
);
1850 if (groupV1
== null && !isSync
) {
1851 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1855 if (groupV1
!= null) {
1856 groupV1
.removeMember(resolveRecipient(source
));
1857 account
.getGroupStore().updateGroup(groupV1
);
1862 if (groupV1
!= null && !isSync
) {
1863 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1868 // Received a group v1 message for a v2 group
1871 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1872 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1873 final var groupMasterKey
= groupContext
.getMasterKey();
1875 getOrMigrateGroup(groupMasterKey
,
1876 groupContext
.getRevision(),
1877 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1881 final var conversationPartnerAddress
= isSync ? destination
: source
;
1882 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1883 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1885 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1886 if (message
.getGroupContext().isPresent()) {
1887 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1888 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1889 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1890 if (group
!= null) {
1891 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1892 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1893 account
.getGroupStore().updateGroup(group
);
1896 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1897 // disappearing message timer already stored in the DecryptedGroup
1899 } else if (conversationPartnerAddress
!= null) {
1900 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1903 if (!ignoreAttachments
) {
1904 if (message
.getAttachments().isPresent()) {
1905 for (var attachment
: message
.getAttachments().get()) {
1906 downloadAttachment(attachment
);
1909 if (message
.getSharedContacts().isPresent()) {
1910 for (var contact
: message
.getSharedContacts().get()) {
1911 if (contact
.getAvatar().isPresent()) {
1912 downloadAttachment(contact
.getAvatar().get().getAttachment());
1917 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1918 final ProfileKey profileKey
;
1920 profileKey
= new ProfileKey(message
.getProfileKey().get());
1921 } catch (InvalidInputException e
) {
1922 throw new AssertionError(e
);
1924 if (source
.matches(account
.getSelfAddress())) {
1925 this.account
.setProfileKey(profileKey
);
1927 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1929 if (message
.getPreviews().isPresent()) {
1930 final var previews
= message
.getPreviews().get();
1931 for (var preview
: previews
) {
1932 if (preview
.getImage().isPresent()) {
1933 downloadAttachment(preview
.getImage().get());
1937 if (message
.getQuote().isPresent()) {
1938 final var quote
= message
.getQuote().get();
1940 for (var quotedAttachment
: quote
.getAttachments()) {
1941 final var thumbnail
= quotedAttachment
.getThumbnail();
1942 if (thumbnail
!= null) {
1943 downloadAttachment(thumbnail
);
1947 if (message
.getSticker().isPresent()) {
1948 final var messageSticker
= message
.getSticker().get();
1949 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1950 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1951 if (sticker
== null) {
1952 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1953 account
.getStickerStore().updateSticker(sticker
);
1955 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, messageSticker
.getPackKey()));
1960 private GroupInfoV2
getOrMigrateGroup(
1961 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1963 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1965 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1966 var groupInfo
= getGroup(groupId
);
1967 final GroupInfoV2 groupInfoV2
;
1968 if (groupInfo
instanceof GroupInfoV1
) {
1969 // Received a v2 group message for a v1 group, we need to locally migrate the group
1970 account
.getGroupStore().deleteGroupV1(((GroupInfoV1
) groupInfo
).getGroupId());
1971 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1972 logger
.info("Locally migrated group {} to group v2, id: {}",
1973 groupInfo
.getGroupId().toBase64(),
1974 groupInfoV2
.getGroupId().toBase64());
1975 } else if (groupInfo
instanceof GroupInfoV2
) {
1976 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1978 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1981 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1982 DecryptedGroup group
= null;
1983 if (signedGroupChange
!= null
1984 && groupInfoV2
.getGroup() != null
1985 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1986 group
= groupV2Helper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(),
1990 if (group
== null) {
1991 group
= groupV2Helper
.getDecryptedGroup(groupSecretParams
);
1993 if (group
!= null) {
1994 storeProfileKeysFromMembers(group
);
1995 final var avatar
= group
.getAvatar();
1996 if (avatar
!= null && !avatar
.isEmpty()) {
1997 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
2000 groupInfoV2
.setGroup(group
, this::resolveRecipient
);
2001 account
.getGroupStore().updateGroup(groupInfoV2
);
2007 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
2008 for (var member
: group
.getMembersList()) {
2009 final var uuid
= UuidUtil
.parseOrThrow(member
.getUuid().toByteArray());
2010 final var recipientId
= account
.getRecipientStore().resolveRecipient(uuid
);
2012 account
.getProfileStore()
2013 .storeProfileKey(recipientId
, new ProfileKey(member
.getProfileKey().toByteArray()));
2014 } catch (InvalidInputException ignored
) {
2019 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
2020 Set
<HandleAction
> queuedActions
= new HashSet
<>();
2021 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
2022 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
2023 if (actions
!= null) {
2024 queuedActions
.addAll(actions
);
2027 for (var action
: queuedActions
) {
2029 action
.execute(this);
2030 } catch (Throwable e
) {
2031 logger
.warn("Message action failed.", e
);
2036 private List
<HandleAction
> retryFailedReceivedMessage(
2037 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
2039 var envelope
= cachedMessage
.loadEnvelope();
2040 if (envelope
== null) {
2043 SignalServiceContent content
= null;
2044 List
<HandleAction
> actions
= null;
2045 if (!envelope
.isReceipt()) {
2047 content
= decryptMessage(envelope
);
2048 } catch (ProtocolUntrustedIdentityException e
) {
2049 if (!envelope
.hasSource()) {
2050 final var identifier
= e
.getSender();
2051 final var recipientId
= resolveRecipient(identifier
);
2053 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
2054 } catch (IOException ioException
) {
2055 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
2059 } catch (Exception er
) {
2060 // All other errors are not recoverable, so delete the cached message
2061 cachedMessage
.delete();
2064 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
2066 handler
.handleMessage(envelope
, content
, null);
2067 cachedMessage
.delete();
2071 public void receiveMessages(
2074 boolean returnOnTimeout
,
2075 boolean ignoreAttachments
,
2076 ReceiveMessageHandler handler
2077 ) throws IOException
{
2078 retryFailedReceivedMessages(handler
, ignoreAttachments
);
2080 Set
<HandleAction
> queuedActions
= null;
2082 final var messagePipe
= getOrCreateMessagePipe();
2084 var hasCaughtUpWithOldMessages
= false;
2086 while (!Thread
.interrupted()) {
2087 SignalServiceEnvelope envelope
;
2088 SignalServiceContent content
= null;
2089 Exception exception
= null;
2090 final CachedMessage
[] cachedMessage
= {null};
2091 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
2092 logger
.debug("Checking for new message from server");
2094 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
2095 final var recipientId
= envelope1
.hasSource()
2096 ?
resolveRecipient(envelope1
.getSourceIdentifier())
2098 // store message on disk, before acknowledging receipt to the server
2099 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
2101 logger
.debug("New message received from server");
2102 if (result
.isPresent()) {
2103 envelope
= result
.get();
2105 // Received indicator that server queue is empty
2106 hasCaughtUpWithOldMessages
= true;
2108 if (queuedActions
!= null) {
2109 for (var action
: queuedActions
) {
2111 action
.execute(this);
2112 } catch (Throwable e
) {
2113 logger
.warn("Message action failed.", e
);
2116 queuedActions
.clear();
2117 queuedActions
= null;
2120 // Continue to wait another timeout for new messages
2123 } catch (TimeoutException e
) {
2124 if (returnOnTimeout
) return;
2128 if (envelope
.hasSource()) {
2129 // Store uuid if we don't have it already
2130 // address/uuid in envelope is sent by server
2131 resolveRecipientTrusted(envelope
.getSourceAddress());
2133 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
2134 if (!envelope
.isReceipt()) {
2136 content
= decryptMessage(envelope
);
2137 } catch (Exception e
) {
2140 if (!envelope
.hasSource() && content
!= null) {
2141 // Store uuid if we don't have it already
2142 // address/uuid is validated by unidentified sender certificate
2143 resolveRecipientTrusted(content
.getSender());
2145 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
2146 if (exception
instanceof ProtocolInvalidMessageException
) {
2147 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
2148 logger
.debug("Received invalid message, queuing renew session action.");
2149 actions
.add(new RenewSessionAction(sender
));
2151 if (hasCaughtUpWithOldMessages
) {
2152 for (var action
: actions
) {
2154 action
.execute(this);
2155 } catch (Throwable e
) {
2156 logger
.warn("Message action failed.", e
);
2160 if (queuedActions
== null) {
2161 queuedActions
= new HashSet
<>();
2163 queuedActions
.addAll(actions
);
2166 if (isMessageBlocked(envelope
, content
)) {
2167 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
2168 } else if (notAGroupMember
) {
2169 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
2171 handler
.handleMessage(envelope
, content
, exception
);
2173 if (cachedMessage
[0] != null) {
2174 if (exception
instanceof ProtocolUntrustedIdentityException
) {
2175 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
2176 final var recipientId
= resolveRecipient(identifier
);
2177 queuedActions
.add(new RetrieveProfileAction(recipientId
));
2178 if (!envelope
.hasSource()) {
2180 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
2181 } catch (IOException ioException
) {
2182 logger
.warn("Failed to move cached message to recipient folder: {}",
2183 ioException
.getMessage());
2187 cachedMessage
[0].delete();
2193 private boolean isMessageBlocked(
2194 SignalServiceEnvelope envelope
, SignalServiceContent content
2196 SignalServiceAddress source
;
2197 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2198 source
= envelope
.getSourceAddress();
2199 } else if (content
!= null) {
2200 source
= content
.getSender();
2204 final var recipientId
= resolveRecipient(source
);
2205 if (isContactBlocked(recipientId
)) {
2209 if (content
!= null && content
.getDataMessage().isPresent()) {
2210 var message
= content
.getDataMessage().get();
2211 if (message
.getGroupContext().isPresent()) {
2212 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2213 var group
= getGroup(groupId
);
2214 if (group
!= null && group
.isBlocked()) {
2222 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
2223 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
2224 return isContactBlocked(recipientId
);
2227 private boolean isContactBlocked(final RecipientId recipientId
) {
2228 var sourceContact
= account
.getContactStore().getContact(recipientId
);
2229 return sourceContact
!= null && sourceContact
.isBlocked();
2232 private boolean isNotAGroupMember(
2233 SignalServiceEnvelope envelope
, SignalServiceContent content
2235 SignalServiceAddress source
;
2236 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2237 source
= envelope
.getSourceAddress();
2238 } else if (content
!= null) {
2239 source
= content
.getSender();
2244 if (content
!= null && content
.getDataMessage().isPresent()) {
2245 var message
= content
.getDataMessage().get();
2246 if (message
.getGroupContext().isPresent()) {
2247 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
2248 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
2249 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
2253 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
2254 var group
= getGroup(groupId
);
2255 if (group
!= null && !group
.isMember(resolveRecipient(source
))) {
2263 private List
<HandleAction
> handleMessage(
2264 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
2266 var actions
= new ArrayList
<HandleAction
>();
2267 if (content
!= null) {
2268 final SignalServiceAddress sender
;
2269 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
2270 sender
= envelope
.getSourceAddress();
2272 sender
= content
.getSender();
2275 if (content
.getDataMessage().isPresent()) {
2276 var message
= content
.getDataMessage().get();
2278 if (content
.isNeedsReceipt()) {
2279 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
2282 actions
.addAll(handleSignalServiceDataMessage(message
,
2285 account
.getSelfAddress(),
2286 ignoreAttachments
));
2288 if (content
.getSyncMessage().isPresent()) {
2289 account
.setMultiDevice(true);
2290 var syncMessage
= content
.getSyncMessage().get();
2291 if (syncMessage
.getSent().isPresent()) {
2292 var message
= syncMessage
.getSent().get();
2293 final var destination
= message
.getDestination().orNull();
2294 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
2298 ignoreAttachments
));
2300 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
2301 var rm
= syncMessage
.getRequest().get();
2302 if (rm
.isContactsRequest()) {
2303 actions
.add(SendSyncContactsAction
.create());
2305 if (rm
.isGroupsRequest()) {
2306 actions
.add(SendSyncGroupsAction
.create());
2308 if (rm
.isBlockedListRequest()) {
2309 actions
.add(SendSyncBlockedListAction
.create());
2311 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2313 if (syncMessage
.getGroups().isPresent()) {
2314 File tmpFile
= null;
2316 tmpFile
= IOUtils
.createTempFile();
2317 final var groupsMessage
= syncMessage
.getGroups().get();
2318 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
2319 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
2324 } catch (IOException e
) {
2325 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
2331 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
2332 if (syncGroup
!= null) {
2333 if (g
.getName().isPresent()) {
2334 syncGroup
.name
= g
.getName().get();
2336 syncGroup
.addMembers(g
.getMembers()
2338 .map(this::resolveRecipient
)
2339 .collect(Collectors
.toSet()));
2340 if (!g
.isActive()) {
2341 syncGroup
.removeMember(account
.getSelfRecipientId());
2343 // Add ourself to the member set as it's marked as active
2344 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
2346 syncGroup
.blocked
= g
.isBlocked();
2347 if (g
.getColor().isPresent()) {
2348 syncGroup
.color
= g
.getColor().get();
2351 if (g
.getAvatar().isPresent()) {
2352 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
2354 syncGroup
.archived
= g
.isArchived();
2355 account
.getGroupStore().updateGroup(syncGroup
);
2359 } catch (Exception e
) {
2360 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2364 if (tmpFile
!= null) {
2366 Files
.delete(tmpFile
.toPath());
2367 } catch (IOException e
) {
2368 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2375 if (syncMessage
.getBlockedList().isPresent()) {
2376 final var blockedListMessage
= syncMessage
.getBlockedList().get();
2377 for (var address
: blockedListMessage
.getAddresses()) {
2378 setContactBlocked(resolveRecipient(address
), true);
2380 for (var groupId
: blockedListMessage
.getGroupIds()
2382 .map(GroupId
::unknownVersion
)
2383 .collect(Collectors
.toSet())) {
2385 setGroupBlocked(groupId
, true);
2386 } catch (GroupNotFoundException e
) {
2387 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2388 groupId
.toBase64());
2392 if (syncMessage
.getContacts().isPresent()) {
2393 File tmpFile
= null;
2395 tmpFile
= IOUtils
.createTempFile();
2396 final var contactsMessage
= syncMessage
.getContacts().get();
2397 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2398 .asPointer(), tmpFile
)) {
2399 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2404 } catch (IOException e
) {
2405 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
2412 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2413 account
.setProfileKey(c
.getProfileKey().get());
2415 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2416 var contact
= account
.getContactStore().getContact(recipientId
);
2417 final var builder
= contact
== null
2418 ? Contact
.newBuilder()
2419 : Contact
.newBuilder(contact
);
2420 if (c
.getName().isPresent()) {
2421 builder
.withName(c
.getName().get());
2423 if (c
.getColor().isPresent()) {
2424 builder
.withColor(c
.getColor().get());
2426 if (c
.getProfileKey().isPresent()) {
2427 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2429 if (c
.getVerified().isPresent()) {
2430 final var verifiedMessage
= c
.getVerified().get();
2431 account
.getIdentityKeyStore()
2432 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2433 verifiedMessage
.getIdentityKey(),
2434 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2436 if (c
.getExpirationTimer().isPresent()) {
2437 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2439 builder
.withBlocked(c
.isBlocked());
2440 builder
.withArchived(c
.isArchived());
2441 account
.getContactStore().storeContact(recipientId
, builder
.build());
2443 if (c
.getAvatar().isPresent()) {
2444 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2448 } catch (Exception e
) {
2449 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2453 if (tmpFile
!= null) {
2455 Files
.delete(tmpFile
.toPath());
2456 } catch (IOException e
) {
2457 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2464 if (syncMessage
.getVerified().isPresent()) {
2465 final var verifiedMessage
= syncMessage
.getVerified().get();
2466 account
.getIdentityKeyStore()
2467 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2468 verifiedMessage
.getIdentityKey(),
2469 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2471 if (syncMessage
.getStickerPackOperations().isPresent()) {
2472 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2473 for (var m
: stickerPackOperationMessages
) {
2474 if (!m
.getPackId().isPresent()) {
2477 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
2478 final var installed
= !m
.getType().isPresent()
2479 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
;
2481 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
2482 if (m
.getPackKey().isPresent()) {
2483 if (sticker
== null) {
2484 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
2487 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, m
.getPackKey().get()));
2491 if (sticker
!= null) {
2492 sticker
.setInstalled(installed
);
2493 account
.getStickerStore().updateSticker(sticker
);
2497 if (syncMessage
.getFetchType().isPresent()) {
2498 switch (syncMessage
.getFetchType().get()) {
2500 getRecipientProfile(account
.getSelfRecipientId(), true);
2501 case STORAGE_MANIFEST
:
2505 if (syncMessage
.getKeys().isPresent()) {
2506 final var keysMessage
= syncMessage
.getKeys().get();
2507 if (keysMessage
.getStorageService().isPresent()) {
2508 final var storageKey
= keysMessage
.getStorageService().get();
2509 account
.setStorageKey(storageKey
);
2512 if (syncMessage
.getConfiguration().isPresent()) {
2520 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2522 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2523 } catch (IOException e
) {
2524 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2528 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2530 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2531 } catch (IOException e
) {
2532 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2536 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2538 avatarStore
.storeGroupAvatar(groupId
,
2539 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2540 } catch (IOException e
) {
2541 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2545 private void downloadProfileAvatar(
2546 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2549 avatarStore
.storeProfileAvatar(address
,
2550 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2551 } catch (Throwable e
) {
2552 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2556 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2557 return attachmentStore
.getAttachmentFile(attachmentId
);
2560 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2561 if (!attachment
.isPointer()) {
2562 logger
.warn("Invalid state, can't store an attachment stream.");
2565 var pointer
= attachment
.asPointer();
2566 if (pointer
.getPreview().isPresent()) {
2567 final var preview
= pointer
.getPreview().get();
2569 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2570 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2571 } catch (IOException e
) {
2572 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2577 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2578 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2579 } catch (IOException e
) {
2580 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2584 private void retrieveGroupV2Avatar(
2585 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2586 ) throws IOException
{
2587 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2589 var tmpFile
= IOUtils
.createTempFile();
2590 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2592 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2593 var encryptedData
= IOUtils
.readFully(input
);
2595 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2596 outputStream
.write(decryptedData
);
2599 Files
.delete(tmpFile
.toPath());
2600 } catch (IOException e
) {
2601 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2608 private void retrieveProfileAvatar(
2609 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2610 ) throws IOException
{
2611 var tmpFile
= IOUtils
.createTempFile();
2612 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2615 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2616 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2617 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2620 Files
.delete(tmpFile
.toPath());
2621 } catch (IOException e
) {
2622 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2629 private void retrieveAttachment(
2630 final SignalServiceAttachment attachment
, final OutputStream outputStream
2631 ) throws IOException
{
2632 if (attachment
.isPointer()) {
2633 var pointer
= attachment
.asPointer();
2634 retrieveAttachmentPointer(pointer
, outputStream
);
2636 var stream
= attachment
.asStream();
2637 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2641 private void retrieveAttachmentPointer(
2642 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2643 ) throws IOException
{
2644 var tmpFile
= IOUtils
.createTempFile();
2645 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2646 IOUtils
.copyStream(input
, outputStream
);
2647 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2648 throw new IOException(e
);
2651 Files
.delete(tmpFile
.toPath());
2652 } catch (IOException e
) {
2653 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2660 private InputStream
retrieveAttachmentAsStream(
2661 SignalServiceAttachmentPointer pointer
, File tmpFile
2662 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2663 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2666 void sendGroups() throws IOException
, UntrustedIdentityException
{
2667 var groupsFile
= IOUtils
.createTempFile();
2670 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2671 var out
= new DeviceGroupsOutputStream(fos
);
2672 for (var record : getGroups()) {
2673 if (record instanceof GroupInfoV1
) {
2674 var groupInfo
= (GroupInfoV1
) record;
2675 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2676 Optional
.fromNullable(groupInfo
.name
),
2677 groupInfo
.getMembers()
2679 .map(this::resolveSignalServiceAddress
)
2680 .collect(Collectors
.toList()),
2681 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2682 groupInfo
.isMember(account
.getSelfRecipientId()),
2683 Optional
.of(groupInfo
.messageExpirationTime
),
2684 Optional
.fromNullable(groupInfo
.color
),
2687 groupInfo
.archived
));
2692 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2693 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2694 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2695 .withStream(groupsFileStream
)
2696 .withContentType("application/octet-stream")
2697 .withLength(groupsFile
.length())
2700 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2705 Files
.delete(groupsFile
.toPath());
2706 } catch (IOException e
) {
2707 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2712 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2713 var contactsFile
= IOUtils
.createTempFile();
2716 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2717 var out
= new DeviceContactsOutputStream(fos
);
2718 for (var contactPair
: account
.getContactStore().getContacts()) {
2719 final var recipientId
= contactPair
.first();
2720 final var contact
= contactPair
.second();
2721 final var address
= resolveSignalServiceAddress(recipientId
);
2723 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2724 VerifiedMessage verifiedMessage
= null;
2725 if (currentIdentity
!= null) {
2726 verifiedMessage
= new VerifiedMessage(address
,
2727 currentIdentity
.getIdentityKey(),
2728 currentIdentity
.getTrustLevel().toVerifiedState(),
2729 currentIdentity
.getDateAdded().getTime());
2732 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2733 out
.write(new DeviceContact(address
,
2734 Optional
.fromNullable(contact
.getName()),
2735 createContactAvatarAttachment(address
),
2736 Optional
.fromNullable(contact
.getColor()),
2737 Optional
.fromNullable(verifiedMessage
),
2738 Optional
.fromNullable(profileKey
),
2739 contact
.isBlocked(),
2740 Optional
.of(contact
.getMessageExpirationTime()),
2742 contact
.isArchived()));
2745 if (account
.getProfileKey() != null) {
2746 // Send our own profile key as well
2747 out
.write(new DeviceContact(account
.getSelfAddress(),
2752 Optional
.of(account
.getProfileKey()),
2760 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2761 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2762 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2763 .withStream(contactsFileStream
)
2764 .withContentType("application/octet-stream")
2765 .withLength(contactsFile
.length())
2768 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2773 Files
.delete(contactsFile
.toPath());
2774 } catch (IOException e
) {
2775 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2780 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2781 var addresses
= new ArrayList
<SignalServiceAddress
>();
2782 for (var record : account
.getContactStore().getContacts()) {
2783 if (record.second().isBlocked()) {
2784 addresses
.add(resolveSignalServiceAddress(record.first()));
2787 var groupIds
= new ArrayList
<byte[]>();
2788 for (var record : getGroups()) {
2789 if (record.isBlocked()) {
2790 groupIds
.add(record.getGroupId().serialize());
2793 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2796 private void sendVerifiedMessage(
2797 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2798 ) throws IOException
, UntrustedIdentityException
{
2799 var verifiedMessage
= new VerifiedMessage(destination
,
2801 trustLevel
.toVerifiedState(),
2802 System
.currentTimeMillis());
2803 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2806 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2807 return account
.getContactStore().getContacts();
2810 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2811 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2812 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2813 if (recipient
== null) {
2817 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2818 return recipient
.getContact().getName();
2821 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2822 return recipient
.getProfile().getDisplayName();
2828 public GroupInfo
getGroup(GroupId groupId
) {
2829 return getGroup(groupId
, false);
2832 public GroupInfo
getGroup(GroupId groupId
, boolean forceUpdate
) {
2833 final var group
= account
.getGroupStore().getGroup(groupId
);
2834 if (group
instanceof GroupInfoV2
&& (forceUpdate
|| ((GroupInfoV2
) group
).getGroup() == null)) {
2835 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2836 ((GroupInfoV2
) group
).setGroup(groupV2Helper
.getDecryptedGroup(groupSecretParams
), this::resolveRecipient
);
2837 account
.getGroupStore().updateGroup(group
);
2842 public List
<IdentityInfo
> getIdentities() {
2843 return account
.getIdentityKeyStore().getIdentities();
2846 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2847 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2848 return identity
== null ? List
.of() : List
.of(identity
);
2852 * Trust this the identity with this fingerprint
2854 * @param name username of the identity
2855 * @param fingerprint Fingerprint
2857 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2858 var recipientId
= canonicalizeAndResolveRecipient(name
);
2859 return trustIdentity(recipientId
,
2860 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2861 TrustLevel
.TRUSTED_VERIFIED
);
2865 * Trust this the identity with this safety number
2867 * @param name username of the identity
2868 * @param safetyNumber Safety number
2870 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2871 var recipientId
= canonicalizeAndResolveRecipient(name
);
2872 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2873 return trustIdentity(recipientId
,
2874 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2875 TrustLevel
.TRUSTED_VERIFIED
);
2879 * Trust all keys of this identity without verification
2881 * @param name username of the identity
2883 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2884 var recipientId
= canonicalizeAndResolveRecipient(name
);
2885 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2888 private boolean trustIdentity(
2889 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2891 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2892 if (identity
== null) {
2896 if (!verifier
.apply(identity
.getIdentityKey())) {
2900 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2902 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2903 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2904 } catch (IOException
| UntrustedIdentityException e
) {
2905 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2911 public String
computeSafetyNumber(
2912 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2914 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2915 account
.getSelfAddress(),
2916 getIdentityKeyPair().getPublicKey(),
2922 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2923 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2925 return resolveSignalServiceAddress(address
);
2929 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2930 if (address
.matches(account
.getSelfAddress())) {
2931 return account
.getSelfAddress();
2934 return account
.getRecipientStore().resolveServiceAddress(address
);
2937 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2938 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2941 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2942 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2944 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2946 return resolveRecipient(canonicalizedNumber
);
2949 private RecipientId
resolveRecipient(final String identifier
) {
2950 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2952 return resolveRecipient(address
);
2955 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2956 return account
.getRecipientStore().resolveRecipient(address
);
2959 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2960 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2963 private void enqueueJob(Job job
) {
2964 var context
= new Context(account
, accountManager
, messageReceiver
, stickerPackStore
);
2969 public void close() throws IOException
{
2973 void close(boolean closeAccount
) throws IOException
{
2974 executor
.shutdown();
2976 if (messagePipe
!= null) {
2977 messagePipe
.shutdown();
2981 if (unidentifiedMessagePipe
!= null) {
2982 unidentifiedMessagePipe
.shutdown();
2983 unidentifiedMessagePipe
= null;
2986 if (closeAccount
&& account
!= null) {
2992 public interface ReceiveMessageHandler
{
2994 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);