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
.Message
;
21 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
22 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
23 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
24 import org
.asamk
.signal
.manager
.api
.TypingAction
;
25 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
26 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
27 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
28 import org
.asamk
.signal
.manager
.groups
.GroupId
;
29 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
30 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
31 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
32 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
33 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
34 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
35 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
36 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
37 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
38 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
39 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
40 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
41 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
42 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
43 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
44 import org
.asamk
.signal
.manager
.jobs
.Context
;
45 import org
.asamk
.signal
.manager
.jobs
.Job
;
46 import org
.asamk
.signal
.manager
.jobs
.RetrieveStickerPackJob
;
47 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
48 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
49 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
50 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
51 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
52 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
56 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
57 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
58 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
59 import org
.asamk
.signal
.manager
.util
.IOUtils
;
60 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
61 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
62 import org
.asamk
.signal
.manager
.util
.Utils
;
63 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
64 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
65 import org
.signal
.zkgroup
.InvalidInputException
;
66 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
67 import org
.slf4j
.Logger
;
68 import org
.slf4j
.LoggerFactory
;
69 import org
.whispersystems
.libsignal
.IdentityKey
;
70 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
71 import org
.whispersystems
.libsignal
.InvalidKeyException
;
72 import org
.whispersystems
.libsignal
.InvalidMessageException
;
73 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
74 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
75 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
76 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
77 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
78 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
79 import org
.whispersystems
.libsignal
.util
.Pair
;
80 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
81 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
82 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
83 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
84 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
85 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
86 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
87 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
88 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
89 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
90 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
91 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
92 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
95 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
96 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
97 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
98 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
99 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
100 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
101 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
102 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
103 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
104 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
107 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
108 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
109 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
110 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
111 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
112 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
113 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
114 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
115 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
116 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
117 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
118 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
119 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
121 import java
.io
.Closeable
;
123 import java
.io
.FileInputStream
;
124 import java
.io
.FileOutputStream
;
125 import java
.io
.IOException
;
126 import java
.io
.InputStream
;
127 import java
.io
.OutputStream
;
129 import java
.net
.URISyntaxException
;
130 import java
.net
.URLEncoder
;
131 import java
.nio
.charset
.StandardCharsets
;
132 import java
.nio
.file
.Files
;
133 import java
.security
.SignatureException
;
134 import java
.util
.ArrayList
;
135 import java
.util
.Arrays
;
136 import java
.util
.Collection
;
137 import java
.util
.Date
;
138 import java
.util
.HashMap
;
139 import java
.util
.HashSet
;
140 import java
.util
.List
;
141 import java
.util
.Map
;
142 import java
.util
.Set
;
143 import java
.util
.UUID
;
144 import java
.util
.concurrent
.ExecutorService
;
145 import java
.util
.concurrent
.Executors
;
146 import java
.util
.concurrent
.TimeUnit
;
147 import java
.util
.concurrent
.TimeoutException
;
148 import java
.util
.concurrent
.locks
.ReentrantLock
;
149 import java
.util
.function
.Function
;
150 import java
.util
.stream
.Collectors
;
152 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
154 public class Manager
implements Closeable
{
156 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
158 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
159 private final SignalDependencies dependencies
;
161 private SignalAccount account
;
163 private final ExecutorService executor
= Executors
.newCachedThreadPool();
165 private final ProfileHelper profileHelper
;
166 private final PinHelper pinHelper
;
167 private final SendHelper sendHelper
;
168 private final GroupHelper groupHelper
;
170 private final AvatarStore avatarStore
;
171 private final AttachmentStore attachmentStore
;
172 private final StickerPackStore stickerPackStore
;
173 private final SignalSessionLock sessionLock
= new SignalSessionLock() {
174 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
177 public Lock
acquire() {
179 return LEGACY_LOCK
::unlock
;
184 SignalAccount account
,
185 PathConfig pathConfig
,
186 ServiceEnvironmentConfig serviceEnvironmentConfig
,
189 this.account
= account
;
190 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
192 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
193 account
.getUsername(),
194 account
.getPassword(),
195 account
.getDeviceId());
196 this.dependencies
= new SignalDependencies(account
.getSelfAddress(),
197 serviceEnvironmentConfig
,
200 account
.getSignalProtocolStore(),
203 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
204 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
205 this.stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
207 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
208 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
209 account
.getProfileStore()::getProfileKey
,
210 this::getRecipientProfile
,
211 this::getSenderCertificate
);
212 this.profileHelper
= new ProfileHelper(account
,
215 account
.getProfileStore()::getProfileKey
,
216 unidentifiedAccessHelper
::getAccessFor
,
217 dependencies
::getProfileService
,
218 dependencies
::getMessageReceiver
,
219 this::resolveSignalServiceAddress
);
220 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
221 this::getRecipientProfile
,
222 account
::getSelfRecipientId
,
223 dependencies
.getGroupsV2Operations(),
224 dependencies
.getGroupsV2Api(),
225 this::resolveSignalServiceAddress
);
226 this.sendHelper
= new SendHelper(account
,
228 unidentifiedAccessHelper
,
229 this::resolveSignalServiceAddress
,
230 this::resolveRecipient
,
231 this::handleIdentityFailure
,
233 this::refreshRegisteredUser
);
234 this.groupHelper
= new GroupHelper(account
,
239 this::resolveSignalServiceAddress
,
240 this::resolveRecipient
);
243 public String
getUsername() {
244 return account
.getUsername();
247 private SignalServiceAddress
getSelfAddress() {
248 return account
.getSelfAddress();
251 public RecipientId
getSelfRecipientId() {
252 return account
.getSelfRecipientId();
255 private IdentityKeyPair
getIdentityKeyPair() {
256 return account
.getIdentityKeyPair();
259 public int getDeviceId() {
260 return account
.getDeviceId();
263 public static Manager
init(
266 ServiceEnvironment serviceEnvironment
,
268 final TrustNewIdentity trustNewIdentity
269 ) throws IOException
, NotRegisteredException
{
270 var pathConfig
= PathConfig
.createDefault(settingsPath
);
272 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
273 throw new NotRegisteredException();
276 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
278 if (!account
.isRegistered()) {
279 throw new NotRegisteredException();
282 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
284 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
287 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
288 var pathConfig
= PathConfig
.createDefault(settingsPath
);
289 final var dataPath
= pathConfig
.getDataPath();
290 final var files
= dataPath
.listFiles();
296 return Arrays
.stream(files
)
297 .filter(File
::isFile
)
299 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
300 .collect(Collectors
.toList());
303 public void checkAccountState() throws IOException
{
304 if (account
.getLastReceiveTimestamp() == 0) {
305 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
307 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
308 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
311 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
315 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
318 if (account
.getUuid() == null) {
319 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
321 updateAccountAttributes();
325 * This is used for checking a set of phone numbers for registration on Signal
327 * @param numbers The set of phone number in question
328 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
329 * @throws IOException if its unable to get the contacts to check if they're registered
331 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
332 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
334 return canonicalizePhoneNumber(n
);
335 } catch (InvalidNumberException e
) {
340 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
341 var contactDetails
= getRegisteredUsers(canonicalizedNumbers
.values()
343 .filter(s
-> !s
.isEmpty())
344 .collect(Collectors
.toSet()));
346 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
347 final var number
= canonicalizedNumbers
.get(n
);
348 final var uuid
= contactDetails
.get(number
);
349 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
353 public void updateAccountAttributes() throws IOException
{
354 dependencies
.getAccountManager()
355 .setAccountAttributes(account
.getEncryptedDeviceName(),
357 account
.getLocalRegistrationId(),
359 // set legacy pin only if no KBS master key is set
360 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
361 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
362 account
.getSelfUnidentifiedAccessKey(),
363 account
.isUnrestrictedUnidentifiedAccess(),
365 account
.isDiscoverableByPhoneNumber());
369 * @param givenName if null, the previous givenName will be kept
370 * @param familyName if null, the previous familyName will be kept
371 * @param about if null, the previous about text will be kept
372 * @param aboutEmoji if null, the previous about emoji will be kept
373 * @param avatar if avatar is null the image from the local avatar store is used (if present),
375 public void setProfile(
376 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
377 ) throws IOException
{
378 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
380 sendSyncFetchProfileMessage();
383 private void sendSyncFetchProfileMessage() throws IOException
{
384 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
387 public void unregister() throws IOException
{
388 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
389 // If this is the master device, other users can't send messages to this number anymore.
390 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
391 dependencies
.getAccountManager().setGcmId(Optional
.absent());
393 account
.setRegistered(false);
396 public void deleteAccount() throws IOException
{
397 dependencies
.getAccountManager().deleteAccount();
399 account
.setRegistered(false);
402 public List
<Device
> getLinkedDevices() throws IOException
{
403 var devices
= dependencies
.getAccountManager().getDevices();
404 account
.setMultiDevice(devices
.size() > 1);
405 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
406 return devices
.stream().map(d
-> {
407 String deviceName
= d
.getName();
408 if (deviceName
!= null) {
410 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
411 } catch (IOException e
) {
412 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
415 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
416 }).collect(Collectors
.toList());
419 public void removeLinkedDevices(int deviceId
) throws IOException
{
420 dependencies
.getAccountManager().removeDevice(deviceId
);
421 var devices
= dependencies
.getAccountManager().getDevices();
422 account
.setMultiDevice(devices
.size() > 1);
425 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
426 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
428 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
431 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
432 var identityKeyPair
= getIdentityKeyPair();
433 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
435 dependencies
.getAccountManager()
436 .addDevice(deviceIdentifier
,
439 Optional
.of(account
.getProfileKey().serialize()),
441 account
.setMultiDevice(true);
444 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
445 if (!account
.isMasterDevice()) {
446 throw new RuntimeException("Only master device can set a PIN");
448 if (pin
.isPresent()) {
449 final var masterKey
= account
.getPinMasterKey() != null
450 ? account
.getPinMasterKey()
451 : KeyUtils
.createMasterKey();
453 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
455 account
.setRegistrationLockPin(pin
.get(), masterKey
);
458 pinHelper
.removeRegistrationLockPin();
460 account
.setRegistrationLockPin(null, null);
464 void refreshPreKeys() throws IOException
{
465 var oneTimePreKeys
= generatePreKeys();
466 final var identityKeyPair
= getIdentityKeyPair();
467 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
469 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
472 private List
<PreKeyRecord
> generatePreKeys() {
473 final var offset
= account
.getPreKeyIdOffset();
475 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
476 account
.addPreKeys(records
);
481 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
482 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
484 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
485 account
.addSignedPreKey(record);
490 public Profile
getRecipientProfile(RecipientId recipientId
) {
491 return profileHelper
.getRecipientProfile(recipientId
);
494 public void refreshRecipientProfile(RecipientId recipientId
) {
495 profileHelper
.refreshRecipientProfile(recipientId
);
498 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
499 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
500 if (streamDetails
== null) {
501 return Optional
.absent();
504 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
507 public List
<GroupInfo
> getGroups() {
508 return account
.getGroupStore().getGroups();
511 public SendGroupMessageResults
quitGroup(
512 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
513 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
514 final var newAdmins
= getRecipientIds(groupAdmins
);
515 return groupHelper
.quitGroup(groupId
, newAdmins
);
518 public void deleteGroup(GroupId groupId
) throws IOException
{
519 account
.getGroupStore().deleteGroup(groupId
);
520 avatarStore
.deleteGroupAvatar(groupId
);
523 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
524 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
525 ) throws IOException
, AttachmentInvalidException
{
526 return groupHelper
.createGroup(name
, members
== null ?
null : getRecipientIds(members
), avatarFile
);
529 public SendGroupMessageResults
updateGroup(
533 Set
<RecipientIdentifier
.Single
> members
,
534 Set
<RecipientIdentifier
.Single
> removeMembers
,
535 Set
<RecipientIdentifier
.Single
> admins
,
536 Set
<RecipientIdentifier
.Single
> removeAdmins
,
537 boolean resetGroupLink
,
538 GroupLinkState groupLinkState
,
539 GroupPermission addMemberPermission
,
540 GroupPermission editDetailsPermission
,
542 Integer expirationTimer
,
543 Boolean isAnnouncementGroup
544 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
545 return groupHelper
.updateGroup(groupId
,
548 members
== null ?
null : getRecipientIds(members
),
549 removeMembers
== null ?
null : getRecipientIds(removeMembers
),
550 admins
== null ?
null : getRecipientIds(admins
),
551 removeAdmins
== null ?
null : getRecipientIds(removeAdmins
),
555 editDetailsPermission
,
558 isAnnouncementGroup
);
561 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
562 GroupInviteLinkUrl inviteLinkUrl
563 ) throws IOException
, GroupLinkNotActiveException
{
564 return groupHelper
.joinGroup(inviteLinkUrl
);
567 public SendMessageResults
sendMessage(
568 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
569 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
570 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
571 long timestamp
= System
.currentTimeMillis();
572 messageBuilder
.withTimestamp(timestamp
);
573 for (final var recipient
: recipients
) {
574 if (recipient
instanceof RecipientIdentifier
.Single
) {
575 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
576 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
577 results
.put(recipient
, List
.of(result
));
578 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
579 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
580 results
.put(recipient
, List
.of(result
));
581 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
582 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
583 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
584 results
.put(recipient
, result
);
587 return new SendMessageResults(timestamp
, results
);
590 public void sendTypingMessage(
591 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
592 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
593 final var timestamp
= System
.currentTimeMillis();
594 for (var recipient
: recipients
) {
595 if (recipient
instanceof RecipientIdentifier
.Single
) {
596 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
597 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
598 sendHelper
.sendTypingMessage(message
, recipientId
);
599 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
600 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
601 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
602 sendHelper
.sendGroupTypingMessage(message
, groupId
);
607 SendGroupMessageResults
sendGroupInfoMessage(
608 GroupIdV1 groupId
, SignalServiceAddress recipient
609 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
610 final var recipientId
= resolveRecipient(recipient
);
611 return groupHelper
.sendGroupInfoMessage(groupId
, recipientId
);
614 SendGroupMessageResults
sendGroupInfoRequest(
615 GroupIdV1 groupId
, SignalServiceAddress recipient
616 ) throws IOException
{
617 final var recipientId
= resolveRecipient(recipient
);
618 return groupHelper
.sendGroupInfoRequest(groupId
, recipientId
);
621 public void sendReadReceipt(
622 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
623 ) throws IOException
, UntrustedIdentityException
{
624 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
626 System
.currentTimeMillis());
628 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
631 public void sendViewedReceipt(
632 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
633 ) throws IOException
, UntrustedIdentityException
{
634 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
636 System
.currentTimeMillis());
638 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
641 void sendDeliveryReceipt(
642 SignalServiceAddress remoteAddress
, List
<Long
> messageIds
643 ) throws IOException
, UntrustedIdentityException
{
644 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
646 System
.currentTimeMillis());
648 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(remoteAddress
));
651 public SendMessageResults
sendMessage(
652 Message message
, Set
<RecipientIdentifier
> recipients
653 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
654 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
655 applyMessage(messageBuilder
, message
);
656 return sendMessage(messageBuilder
, recipients
);
659 private void applyMessage(
660 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
661 ) throws AttachmentInvalidException
, IOException
{
662 messageBuilder
.withBody(message
.getMessageText());
663 if (message
.getAttachments() != null) {
664 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(message
.getAttachments());
666 // Upload attachments here, so we only upload once even for multiple recipients
667 var messageSender
= dependencies
.getMessageSender();
668 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
669 for (var attachment
: attachmentStreams
) {
670 if (attachment
.isStream()) {
671 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
672 } else if (attachment
.isPointer()) {
673 attachmentPointers
.add(attachment
.asPointer());
677 messageBuilder
.withAttachments(attachmentPointers
);
681 public SendMessageResults
sendRemoteDeleteMessage(
682 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
683 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
684 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
685 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
686 return sendMessage(messageBuilder
, recipients
);
689 public SendMessageResults
sendMessageReaction(
692 RecipientIdentifier
.Single targetAuthor
,
693 long targetSentTimestamp
,
694 Set
<RecipientIdentifier
> recipients
695 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
696 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
697 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
699 resolveSignalServiceAddress(targetAuthorRecipientId
),
700 targetSentTimestamp
);
701 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
702 return sendMessage(messageBuilder
, recipients
);
705 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
706 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
709 return sendMessage(messageBuilder
,
710 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
711 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
712 throw new AssertionError(e
);
714 for (var recipient
: recipients
) {
715 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
716 handleEndSession(recipientId
);
721 void renewSession(RecipientId recipientId
) throws IOException
{
722 account
.getSessionStore().archiveSessions(recipientId
);
723 if (!recipientId
.equals(getSelfRecipientId())) {
724 sendHelper
.sendNullMessage(recipientId
);
728 public void setContactName(
729 RecipientIdentifier
.Single recipient
, String name
730 ) throws NotMasterDeviceException
{
731 if (!account
.isMasterDevice()) {
732 throw new NotMasterDeviceException();
734 final var recipientId
= resolveRecipient(recipient
);
735 var contact
= account
.getContactStore().getContact(recipientId
);
736 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
737 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
740 public void setContactBlocked(
741 RecipientIdentifier
.Single recipient
, boolean blocked
742 ) throws NotMasterDeviceException
{
743 if (!account
.isMasterDevice()) {
744 throw new NotMasterDeviceException();
746 setContactBlocked(resolveRecipient(recipient
), blocked
);
749 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
750 var contact
= account
.getContactStore().getContact(recipientId
);
751 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
752 // TODO cycle our profile key
753 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
756 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
757 var group
= getGroup(groupId
);
759 throw new GroupNotFoundException(groupId
);
762 group
.setBlocked(blocked
);
763 // TODO cycle our profile key
764 account
.getGroupStore().updateGroup(group
);
768 * Change the expiration timer for a contact
770 public void setExpirationTimer(
771 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
772 ) throws IOException
{
773 var recipientId
= resolveRecipient(recipient
);
774 setExpirationTimer(recipientId
, messageExpirationTimer
);
775 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
777 sendMessage(messageBuilder
, Set
.of(recipient
));
778 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
779 throw new AssertionError(e
);
783 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
784 var contact
= account
.getContactStore().getContact(recipientId
);
785 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
788 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
789 account
.getContactStore()
790 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
794 * Upload the sticker pack from path.
796 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
797 * @return if successful, returns the URL to install the sticker pack in the signal app
799 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
800 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
802 var messageSender
= dependencies
.getMessageSender();
804 var packKey
= KeyUtils
.createStickerUploadKey();
805 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
806 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
808 var sticker
= new Sticker(packId
, packKey
);
809 account
.getStickerStore().updateSticker(sticker
);
812 return new URI("https",
816 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
818 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
819 } catch (URISyntaxException e
) {
820 throw new AssertionError(e
);
824 public void requestAllSyncData() throws IOException
{
826 requestSyncContacts();
827 requestSyncBlocked();
828 requestSyncConfiguration();
832 private void requestSyncGroups() throws IOException
{
833 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
834 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
836 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
837 sendHelper
.sendSyncMessage(message
);
840 private void requestSyncContacts() throws IOException
{
841 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
842 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
844 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
845 sendHelper
.sendSyncMessage(message
);
848 private void requestSyncBlocked() throws IOException
{
849 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
850 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
852 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
853 sendHelper
.sendSyncMessage(message
);
856 private void requestSyncConfiguration() throws IOException
{
857 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
858 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
860 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
861 sendHelper
.sendSyncMessage(message
);
864 private void requestSyncKeys() throws IOException
{
865 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
866 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
868 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
869 sendHelper
.sendSyncMessage(message
);
872 private byte[] getSenderCertificate() {
875 if (account
.isPhoneNumberShared()) {
876 certificate
= dependencies
.getAccountManager().getSenderCertificate();
878 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
880 } catch (IOException e
) {
881 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
884 // TODO cache for a day
888 private Set
<RecipientId
> getRecipientIds(Collection
<RecipientIdentifier
.Single
> recipients
) {
889 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(recipients
.size());
890 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
892 for (var number
: recipients
) {
893 final var resolvedAddress
= resolveSignalServiceAddress(resolveRecipient(number
));
894 if (resolvedAddress
.getUuid().isPresent()) {
895 signalServiceAddresses
.add(resolvedAddress
);
897 addressesMissingUuid
.add(resolvedAddress
);
901 final var numbersMissingUuid
= addressesMissingUuid
.stream()
902 .map(a
-> a
.getNumber().get())
903 .collect(Collectors
.toSet());
904 Map
<String
, UUID
> registeredUsers
;
906 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
907 } catch (IOException e
) {
908 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
909 registeredUsers
= Map
.of();
912 for (var address
: addressesMissingUuid
) {
913 final var number
= address
.getNumber().get();
914 if (registeredUsers
.containsKey(number
)) {
915 final var newAddress
= resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
916 registeredUsers
.get(number
),
918 signalServiceAddresses
.add(newAddress
);
920 signalServiceAddresses
.add(address
);
924 return signalServiceAddresses
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
927 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
928 final var address
= resolveSignalServiceAddress(recipientId
);
929 if (!address
.getNumber().isPresent()) {
932 final var number
= address
.getNumber().get();
933 final var uuidMap
= getRegisteredUsers(Set
.of(number
));
934 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap
.getOrDefault(number
, null), number
));
937 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
938 final Map
<String
, UUID
> registeredUsers
;
940 registeredUsers
= dependencies
.getAccountManager()
941 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
943 serviceEnvironmentConfig
.getCdsMrenclave());
944 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
945 throw new IOException(e
);
948 // Store numbers as recipients so we have the number/uuid association
949 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
951 return registeredUsers
;
954 public void sendTypingMessage(
955 TypingAction action
, Set
<RecipientIdentifier
> recipients
956 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
957 sendTypingMessage(action
.toSignalService(), recipients
);
960 private void handleEndSession(RecipientId recipientId
) {
961 account
.getSessionStore().deleteAllSessions(recipientId
);
964 private List
<HandleAction
> handleSignalServiceDataMessage(
965 SignalServiceDataMessage message
,
967 SignalServiceAddress source
,
968 SignalServiceAddress destination
,
969 boolean ignoreAttachments
971 var actions
= new ArrayList
<HandleAction
>();
972 if (message
.getGroupContext().isPresent()) {
973 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
974 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
975 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
976 var group
= getGroup(groupId
);
977 if (group
== null || group
instanceof GroupInfoV1
) {
978 var groupV1
= (GroupInfoV1
) group
;
979 switch (groupInfo
.getType()) {
981 if (groupV1
== null) {
982 groupV1
= new GroupInfoV1(groupId
);
985 if (groupInfo
.getAvatar().isPresent()) {
986 var avatar
= groupInfo
.getAvatar().get();
987 downloadGroupAvatar(groupV1
.getGroupId(), avatar
);
990 if (groupInfo
.getName().isPresent()) {
991 groupV1
.name
= groupInfo
.getName().get();
994 if (groupInfo
.getMembers().isPresent()) {
995 groupV1
.addMembers(groupInfo
.getMembers()
998 .map(this::resolveRecipient
)
999 .collect(Collectors
.toSet()));
1002 account
.getGroupStore().updateGroup(groupV1
);
1006 if (groupV1
== null && !isSync
) {
1007 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1011 if (groupV1
!= null) {
1012 groupV1
.removeMember(resolveRecipient(source
));
1013 account
.getGroupStore().updateGroup(groupV1
);
1018 if (groupV1
!= null && !isSync
) {
1019 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1024 // Received a group v1 message for a v2 group
1027 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1028 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1029 final var groupMasterKey
= groupContext
.getMasterKey();
1031 groupHelper
.getOrMigrateGroup(groupMasterKey
,
1032 groupContext
.getRevision(),
1033 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1037 final var conversationPartnerAddress
= isSync ? destination
: source
;
1038 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1039 handleEndSession(resolveRecipient(conversationPartnerAddress
));
1041 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1042 if (message
.getGroupContext().isPresent()) {
1043 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1044 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1045 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1046 if (group
!= null) {
1047 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1048 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1049 account
.getGroupStore().updateGroup(group
);
1052 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1053 // disappearing message timer already stored in the DecryptedGroup
1055 } else if (conversationPartnerAddress
!= null) {
1056 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1059 if (!ignoreAttachments
) {
1060 if (message
.getAttachments().isPresent()) {
1061 for (var attachment
: message
.getAttachments().get()) {
1062 downloadAttachment(attachment
);
1065 if (message
.getSharedContacts().isPresent()) {
1066 for (var contact
: message
.getSharedContacts().get()) {
1067 if (contact
.getAvatar().isPresent()) {
1068 downloadAttachment(contact
.getAvatar().get().getAttachment());
1073 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1074 final ProfileKey profileKey
;
1076 profileKey
= new ProfileKey(message
.getProfileKey().get());
1077 } catch (InvalidInputException e
) {
1078 throw new AssertionError(e
);
1080 if (source
.matches(account
.getSelfAddress())) {
1081 this.account
.setProfileKey(profileKey
);
1083 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1085 if (message
.getPreviews().isPresent()) {
1086 final var previews
= message
.getPreviews().get();
1087 for (var preview
: previews
) {
1088 if (preview
.getImage().isPresent()) {
1089 downloadAttachment(preview
.getImage().get());
1093 if (message
.getQuote().isPresent()) {
1094 final var quote
= message
.getQuote().get();
1096 for (var quotedAttachment
: quote
.getAttachments()) {
1097 final var thumbnail
= quotedAttachment
.getThumbnail();
1098 if (thumbnail
!= null) {
1099 downloadAttachment(thumbnail
);
1103 if (message
.getSticker().isPresent()) {
1104 final var messageSticker
= message
.getSticker().get();
1105 final var stickerPackId
= StickerPackId
.deserialize(messageSticker
.getPackId());
1106 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1107 if (sticker
== null) {
1108 sticker
= new Sticker(stickerPackId
, messageSticker
.getPackKey());
1109 account
.getStickerStore().updateSticker(sticker
);
1111 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, messageSticker
.getPackKey()));
1116 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1117 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1118 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1119 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1120 if (actions
!= null) {
1121 queuedActions
.addAll(actions
);
1124 handleQueuedActions(queuedActions
);
1127 private List
<HandleAction
> retryFailedReceivedMessage(
1128 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1130 var envelope
= cachedMessage
.loadEnvelope();
1131 if (envelope
== null) {
1134 SignalServiceContent content
= null;
1135 List
<HandleAction
> actions
= null;
1136 if (!envelope
.isReceipt()) {
1138 content
= dependencies
.getCipher().decrypt(envelope
);
1139 } catch (ProtocolUntrustedIdentityException e
) {
1140 if (!envelope
.hasSource()) {
1141 final var identifier
= e
.getSender();
1142 final var recipientId
= resolveRecipient(identifier
);
1144 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1145 } catch (IOException ioException
) {
1146 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1150 } catch (Exception er
) {
1151 // All other errors are not recoverable, so delete the cached message
1152 cachedMessage
.delete();
1155 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1157 handler
.handleMessage(envelope
, content
, null);
1158 cachedMessage
.delete();
1162 public void receiveMessages(
1165 boolean returnOnTimeout
,
1166 boolean ignoreAttachments
,
1167 ReceiveMessageHandler handler
1168 ) throws IOException
{
1169 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1171 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1173 final var signalWebSocket
= dependencies
.getSignalWebSocket();
1174 signalWebSocket
.connect();
1176 var hasCaughtUpWithOldMessages
= false;
1178 while (!Thread
.interrupted()) {
1179 SignalServiceEnvelope envelope
;
1180 SignalServiceContent content
= null;
1181 Exception exception
= null;
1182 final CachedMessage
[] cachedMessage
= {null};
1183 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
1184 logger
.debug("Checking for new message from server");
1186 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
1187 final var recipientId
= envelope1
.hasSource()
1188 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1190 // store message on disk, before acknowledging receipt to the server
1191 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1193 logger
.debug("New message received from server");
1194 if (result
.isPresent()) {
1195 envelope
= result
.get();
1197 // Received indicator that server queue is empty
1198 hasCaughtUpWithOldMessages
= true;
1200 handleQueuedActions(queuedActions
);
1201 queuedActions
.clear();
1203 // Continue to wait another timeout for new messages
1206 } catch (AssertionError e
) {
1207 if (e
.getCause() instanceof InterruptedException
) {
1208 Thread
.currentThread().interrupt();
1213 } catch (WebSocketUnavailableException e
) {
1214 logger
.debug("Pipe unexpectedly unavailable, connecting");
1215 signalWebSocket
.connect();
1217 } catch (TimeoutException e
) {
1218 if (returnOnTimeout
) return;
1222 if (envelope
.hasSource()) {
1223 // Store uuid if we don't have it already
1224 // address/uuid in envelope is sent by server
1225 resolveRecipientTrusted(envelope
.getSourceAddress());
1227 if (!envelope
.isReceipt()) {
1229 content
= dependencies
.getCipher().decrypt(envelope
);
1230 } catch (Exception e
) {
1233 if (!envelope
.hasSource() && content
!= null) {
1234 // Store uuid if we don't have it already
1235 // address/uuid is validated by unidentified sender certificate
1236 resolveRecipientTrusted(content
.getSender());
1238 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1239 if (exception
instanceof ProtocolInvalidMessageException
) {
1240 final var sender
= resolveRecipient(((ProtocolInvalidMessageException
) exception
).getSender());
1241 logger
.debug("Received invalid message, queuing renew session action.");
1242 actions
.add(new RenewSessionAction(sender
));
1244 if (hasCaughtUpWithOldMessages
) {
1245 for (var action
: actions
) {
1247 action
.execute(this);
1248 } catch (Throwable e
) {
1249 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1250 Thread
.currentThread().interrupt();
1252 logger
.warn("Message action failed.", e
);
1256 queuedActions
.addAll(actions
);
1259 final var notAllowedToSendToGroup
= isNotAllowedToSendToGroup(envelope
, content
);
1260 if (isMessageBlocked(envelope
, content
)) {
1261 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1262 } else if (notAllowedToSendToGroup
) {
1263 logger
.info("Ignoring a group message from an unauthorized sender (no member or admin): {} {}",
1264 (envelope
.hasSource() ? envelope
.getSourceAddress() : content
.getSender()).getIdentifier(),
1265 envelope
.getTimestamp());
1267 handler
.handleMessage(envelope
, content
, exception
);
1269 if (cachedMessage
[0] != null) {
1270 if (exception
instanceof ProtocolUntrustedIdentityException
) {
1271 final var identifier
= ((ProtocolUntrustedIdentityException
) exception
).getSender();
1272 final var recipientId
= resolveRecipient(identifier
);
1273 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1274 if (!envelope
.hasSource()) {
1276 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1277 } catch (IOException ioException
) {
1278 logger
.warn("Failed to move cached message to recipient folder: {}",
1279 ioException
.getMessage());
1283 cachedMessage
[0].delete();
1287 handleQueuedActions(queuedActions
);
1290 private void handleQueuedActions(final Set
<HandleAction
> queuedActions
) {
1291 for (var action
: queuedActions
) {
1293 action
.execute(this);
1294 } catch (Throwable e
) {
1295 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
1296 Thread
.currentThread().interrupt();
1298 logger
.warn("Message action failed.", e
);
1303 private boolean isMessageBlocked(
1304 SignalServiceEnvelope envelope
, SignalServiceContent content
1306 SignalServiceAddress source
;
1307 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1308 source
= envelope
.getSourceAddress();
1309 } else if (content
!= null) {
1310 source
= content
.getSender();
1314 final var recipientId
= resolveRecipient(source
);
1315 if (isContactBlocked(recipientId
)) {
1319 if (content
!= null && content
.getDataMessage().isPresent()) {
1320 var message
= content
.getDataMessage().get();
1321 if (message
.getGroupContext().isPresent()) {
1322 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1323 var group
= getGroup(groupId
);
1324 if (group
!= null && group
.isBlocked()) {
1332 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1333 final var recipientId
= resolveRecipient(recipient
);
1334 return isContactBlocked(recipientId
);
1337 private boolean isContactBlocked(final RecipientId recipientId
) {
1338 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1339 return sourceContact
!= null && sourceContact
.isBlocked();
1342 private boolean isNotAllowedToSendToGroup(
1343 SignalServiceEnvelope envelope
, SignalServiceContent content
1345 SignalServiceAddress source
;
1346 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1347 source
= envelope
.getSourceAddress();
1348 } else if (content
!= null) {
1349 source
= content
.getSender();
1354 if (content
== null || !content
.getDataMessage().isPresent()) {
1358 var message
= content
.getDataMessage().get();
1359 if (!message
.getGroupContext().isPresent()) {
1363 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1364 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1365 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1370 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1371 var group
= getGroup(groupId
);
1372 if (group
== null) {
1376 final var recipientId
= resolveRecipient(source
);
1377 if (!group
.isMember(recipientId
)) {
1381 if (group
.isAnnouncementGroup() && !group
.isAdmin(recipientId
)) {
1382 return message
.getBody().isPresent()
1383 || message
.getAttachments().isPresent()
1384 || message
.getQuote()
1386 || message
.getPreviews().isPresent()
1387 || message
.getMentions().isPresent()
1388 || message
.getSticker().isPresent();
1393 private List
<HandleAction
> handleMessage(
1394 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1396 var actions
= new ArrayList
<HandleAction
>();
1397 if (content
!= null) {
1398 final SignalServiceAddress sender
;
1399 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1400 sender
= envelope
.getSourceAddress();
1402 sender
= content
.getSender();
1405 if (content
.getDataMessage().isPresent()) {
1406 var message
= content
.getDataMessage().get();
1408 if (content
.isNeedsReceipt()) {
1409 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1412 actions
.addAll(handleSignalServiceDataMessage(message
,
1415 account
.getSelfAddress(),
1416 ignoreAttachments
));
1418 if (content
.getSyncMessage().isPresent()) {
1419 account
.setMultiDevice(true);
1420 var syncMessage
= content
.getSyncMessage().get();
1421 if (syncMessage
.getSent().isPresent()) {
1422 var message
= syncMessage
.getSent().get();
1423 final var destination
= message
.getDestination().orNull();
1424 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1428 ignoreAttachments
));
1430 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1431 var rm
= syncMessage
.getRequest().get();
1432 if (rm
.isContactsRequest()) {
1433 actions
.add(SendSyncContactsAction
.create());
1435 if (rm
.isGroupsRequest()) {
1436 actions
.add(SendSyncGroupsAction
.create());
1438 if (rm
.isBlockedListRequest()) {
1439 actions
.add(SendSyncBlockedListAction
.create());
1441 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1443 if (syncMessage
.getGroups().isPresent()) {
1444 File tmpFile
= null;
1446 tmpFile
= IOUtils
.createTempFile();
1447 final var groupsMessage
= syncMessage
.getGroups().get();
1448 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1449 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1454 } catch (IOException e
) {
1455 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
1461 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1462 if (syncGroup
!= null) {
1463 if (g
.getName().isPresent()) {
1464 syncGroup
.name
= g
.getName().get();
1466 syncGroup
.addMembers(g
.getMembers()
1468 .map(this::resolveRecipient
)
1469 .collect(Collectors
.toSet()));
1470 if (!g
.isActive()) {
1471 syncGroup
.removeMember(account
.getSelfRecipientId());
1473 // Add ourself to the member set as it's marked as active
1474 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
1476 syncGroup
.blocked
= g
.isBlocked();
1477 if (g
.getColor().isPresent()) {
1478 syncGroup
.color
= g
.getColor().get();
1481 if (g
.getAvatar().isPresent()) {
1482 downloadGroupAvatar(syncGroup
.getGroupId(), g
.getAvatar().get());
1484 syncGroup
.archived
= g
.isArchived();
1485 account
.getGroupStore().updateGroup(syncGroup
);
1489 } catch (Exception e
) {
1490 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1494 if (tmpFile
!= null) {
1496 Files
.delete(tmpFile
.toPath());
1497 } catch (IOException e
) {
1498 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1505 if (syncMessage
.getBlockedList().isPresent()) {
1506 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1507 for (var address
: blockedListMessage
.getAddresses()) {
1508 setContactBlocked(resolveRecipient(address
), true);
1510 for (var groupId
: blockedListMessage
.getGroupIds()
1512 .map(GroupId
::unknownVersion
)
1513 .collect(Collectors
.toSet())) {
1515 setGroupBlocked(groupId
, true);
1516 } catch (GroupNotFoundException e
) {
1517 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1518 groupId
.toBase64());
1522 if (syncMessage
.getContacts().isPresent()) {
1523 File tmpFile
= null;
1525 tmpFile
= IOUtils
.createTempFile();
1526 final var contactsMessage
= syncMessage
.getContacts().get();
1527 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1528 .asPointer(), tmpFile
)) {
1529 var s
= new DeviceContactsInputStream(attachmentAsStream
);
1534 } catch (IOException e
) {
1535 logger
.warn("Sync contacts contained invalid contact, ignoring: {}",
1542 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1543 account
.setProfileKey(c
.getProfileKey().get());
1545 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
1546 var contact
= account
.getContactStore().getContact(recipientId
);
1547 final var builder
= contact
== null
1548 ? Contact
.newBuilder()
1549 : Contact
.newBuilder(contact
);
1550 if (c
.getName().isPresent()) {
1551 builder
.withName(c
.getName().get());
1553 if (c
.getColor().isPresent()) {
1554 builder
.withColor(c
.getColor().get());
1556 if (c
.getProfileKey().isPresent()) {
1557 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
1559 if (c
.getVerified().isPresent()) {
1560 final var verifiedMessage
= c
.getVerified().get();
1561 account
.getIdentityKeyStore()
1562 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
1563 verifiedMessage
.getIdentityKey(),
1564 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1566 if (c
.getExpirationTimer().isPresent()) {
1567 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
1569 builder
.withBlocked(c
.isBlocked());
1570 builder
.withArchived(c
.isArchived());
1571 account
.getContactStore().storeContact(recipientId
, builder
.build());
1573 if (c
.getAvatar().isPresent()) {
1574 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
1578 } catch (Exception e
) {
1579 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1583 if (tmpFile
!= null) {
1585 Files
.delete(tmpFile
.toPath());
1586 } catch (IOException e
) {
1587 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1594 if (syncMessage
.getVerified().isPresent()) {
1595 final var verifiedMessage
= syncMessage
.getVerified().get();
1596 account
.getIdentityKeyStore()
1597 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
1598 verifiedMessage
.getIdentityKey(),
1599 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1601 if (syncMessage
.getStickerPackOperations().isPresent()) {
1602 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
1603 for (var m
: stickerPackOperationMessages
) {
1604 if (!m
.getPackId().isPresent()) {
1607 final var stickerPackId
= StickerPackId
.deserialize(m
.getPackId().get());
1608 final var installed
= !m
.getType().isPresent()
1609 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
;
1611 var sticker
= account
.getStickerStore().getSticker(stickerPackId
);
1612 if (m
.getPackKey().isPresent()) {
1613 if (sticker
== null) {
1614 sticker
= new Sticker(stickerPackId
, m
.getPackKey().get());
1617 enqueueJob(new RetrieveStickerPackJob(stickerPackId
, m
.getPackKey().get()));
1621 if (sticker
!= null) {
1622 sticker
.setInstalled(installed
);
1623 account
.getStickerStore().updateSticker(sticker
);
1627 if (syncMessage
.getFetchType().isPresent()) {
1628 switch (syncMessage
.getFetchType().get()) {
1630 actions
.add(new RetrieveProfileAction(account
.getSelfRecipientId()));
1631 case STORAGE_MANIFEST
:
1635 if (syncMessage
.getKeys().isPresent()) {
1636 final var keysMessage
= syncMessage
.getKeys().get();
1637 if (keysMessage
.getStorageService().isPresent()) {
1638 final var storageKey
= keysMessage
.getStorageService().get();
1639 account
.setStorageKey(storageKey
);
1642 if (syncMessage
.getConfiguration().isPresent()) {
1650 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
1652 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1653 } catch (IOException e
) {
1654 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
1658 private void downloadGroupAvatar(GroupIdV1 groupId
, SignalServiceAttachment avatar
) {
1660 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
1661 } catch (IOException e
) {
1662 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
1666 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1667 return attachmentStore
.getAttachmentFile(attachmentId
);
1670 private void downloadAttachment(final SignalServiceAttachment attachment
) {
1671 if (!attachment
.isPointer()) {
1672 logger
.warn("Invalid state, can't store an attachment stream.");
1675 var pointer
= attachment
.asPointer();
1676 if (pointer
.getPreview().isPresent()) {
1677 final var preview
= pointer
.getPreview().get();
1679 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
1680 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
1681 } catch (IOException e
) {
1682 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
1687 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
1688 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
1689 } catch (IOException e
) {
1690 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
1694 private void retrieveAttachment(
1695 final SignalServiceAttachment attachment
, final OutputStream outputStream
1696 ) throws IOException
{
1697 if (attachment
.isPointer()) {
1698 var pointer
= attachment
.asPointer();
1699 retrieveAttachmentPointer(pointer
, outputStream
);
1701 var stream
= attachment
.asStream();
1702 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
1706 private void retrieveAttachmentPointer(
1707 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
1708 ) throws IOException
{
1709 var tmpFile
= IOUtils
.createTempFile();
1710 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
1711 IOUtils
.copyStream(input
, outputStream
);
1712 } catch (MissingConfigurationException
| InvalidMessageException e
) {
1713 throw new IOException(e
);
1716 Files
.delete(tmpFile
.toPath());
1717 } catch (IOException e
) {
1718 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
1725 private InputStream
retrieveAttachmentAsStream(
1726 SignalServiceAttachmentPointer pointer
, File tmpFile
1727 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
1728 return dependencies
.getMessageReceiver()
1729 .retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
1732 void sendGroups() throws IOException
{
1733 var groupsFile
= IOUtils
.createTempFile();
1736 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1737 var out
= new DeviceGroupsOutputStream(fos
);
1738 for (var record : getGroups()) {
1739 if (record instanceof GroupInfoV1
) {
1740 var groupInfo
= (GroupInfoV1
) record;
1741 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
1742 Optional
.fromNullable(groupInfo
.name
),
1743 groupInfo
.getMembers()
1745 .map(this::resolveSignalServiceAddress
)
1746 .collect(Collectors
.toList()),
1747 groupHelper
.createGroupAvatarAttachment(groupInfo
.getGroupId()),
1748 groupInfo
.isMember(account
.getSelfRecipientId()),
1749 Optional
.of(groupInfo
.messageExpirationTime
),
1750 Optional
.fromNullable(groupInfo
.color
),
1753 groupInfo
.archived
));
1758 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1759 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
1760 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1761 .withStream(groupsFileStream
)
1762 .withContentType("application/octet-stream")
1763 .withLength(groupsFile
.length())
1766 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1771 Files
.delete(groupsFile
.toPath());
1772 } catch (IOException e
) {
1773 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
1778 public void sendContacts() throws IOException
{
1779 var contactsFile
= IOUtils
.createTempFile();
1782 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1783 var out
= new DeviceContactsOutputStream(fos
);
1784 for (var contactPair
: account
.getContactStore().getContacts()) {
1785 final var recipientId
= contactPair
.first();
1786 final var contact
= contactPair
.second();
1787 final var address
= resolveSignalServiceAddress(recipientId
);
1789 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1790 VerifiedMessage verifiedMessage
= null;
1791 if (currentIdentity
!= null) {
1792 verifiedMessage
= new VerifiedMessage(address
,
1793 currentIdentity
.getIdentityKey(),
1794 currentIdentity
.getTrustLevel().toVerifiedState(),
1795 currentIdentity
.getDateAdded().getTime());
1798 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
1799 out
.write(new DeviceContact(address
,
1800 Optional
.fromNullable(contact
.getName()),
1801 createContactAvatarAttachment(address
),
1802 Optional
.fromNullable(contact
.getColor()),
1803 Optional
.fromNullable(verifiedMessage
),
1804 Optional
.fromNullable(profileKey
),
1805 contact
.isBlocked(),
1806 Optional
.of(contact
.getMessageExpirationTime()),
1808 contact
.isArchived()));
1811 if (account
.getProfileKey() != null) {
1812 // Send our own profile key as well
1813 out
.write(new DeviceContact(account
.getSelfAddress(),
1818 Optional
.of(account
.getProfileKey()),
1826 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1827 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
1828 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1829 .withStream(contactsFileStream
)
1830 .withContentType("application/octet-stream")
1831 .withLength(contactsFile
.length())
1834 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
,
1840 Files
.delete(contactsFile
.toPath());
1841 } catch (IOException e
) {
1842 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
1847 void sendBlockedList() throws IOException
{
1848 var addresses
= new ArrayList
<SignalServiceAddress
>();
1849 for (var record : account
.getContactStore().getContacts()) {
1850 if (record.second().isBlocked()) {
1851 addresses
.add(resolveSignalServiceAddress(record.first()));
1854 var groupIds
= new ArrayList
<byte[]>();
1855 for (var record : getGroups()) {
1856 if (record.isBlocked()) {
1857 groupIds
.add(record.getGroupId().serialize());
1860 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
1863 private void sendVerifiedMessage(
1864 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
1865 ) throws IOException
{
1866 var verifiedMessage
= new VerifiedMessage(destination
,
1868 trustLevel
.toVerifiedState(),
1869 System
.currentTimeMillis());
1870 sendHelper
.sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1873 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
1874 return account
.getContactStore().getContacts();
1877 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
1878 final var recipientId
= resolveRecipient(recipientIdentifier
);
1880 final var contact
= account
.getRecipientStore().getContact(recipientId
);
1881 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1882 return contact
.getName();
1885 final var profile
= getRecipientProfile(recipientId
);
1886 if (profile
!= null) {
1887 return profile
.getDisplayName();
1893 public GroupInfo
getGroup(GroupId groupId
) {
1894 return groupHelper
.getGroup(groupId
);
1897 public List
<IdentityInfo
> getIdentities() {
1898 return account
.getIdentityKeyStore().getIdentities();
1901 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1902 final var identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1903 return identity
== null ? List
.of() : List
.of(identity
);
1907 * Trust this the identity with this fingerprint
1909 * @param recipient username of the identity
1910 * @param fingerprint Fingerprint
1912 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1913 var recipientId
= resolveRecipient(recipient
);
1914 return trustIdentity(recipientId
,
1915 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1916 TrustLevel
.TRUSTED_VERIFIED
);
1920 * Trust this the identity with this safety number
1922 * @param recipient username of the identity
1923 * @param safetyNumber Safety number
1925 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1926 var recipientId
= resolveRecipient(recipient
);
1927 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
1928 return trustIdentity(recipientId
,
1929 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1930 TrustLevel
.TRUSTED_VERIFIED
);
1934 * Trust this the identity with this scannable safety number
1936 * @param recipient username of the identity
1937 * @param safetyNumber Scannable safety number
1939 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1940 var recipientId
= resolveRecipient(recipient
);
1941 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
1942 return trustIdentity(recipientId
, identityKey
-> {
1943 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1945 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1946 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1949 }, TrustLevel
.TRUSTED_VERIFIED
);
1953 * Trust all keys of this identity without verification
1955 * @param recipient username of the identity
1957 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1958 var recipientId
= resolveRecipient(recipient
);
1959 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1962 private boolean trustIdentity(
1963 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1965 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1966 if (identity
== null) {
1970 if (!verifier
.apply(identity
.getIdentityKey())) {
1974 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1976 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
1977 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1978 } catch (IOException e
) {
1979 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1985 private void handleIdentityFailure(
1986 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1988 final var identityKey
= identityFailure
.getIdentityKey();
1989 if (identityKey
!= null) {
1990 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1992 account
.getSessionStore().archiveSessions(recipientId
);
1995 // Retrieve profile to get the current identity key from the server
1996 refreshRecipientProfile(recipientId
);
2000 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
2001 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
2002 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
2005 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
2006 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
2007 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
2010 private Fingerprint
computeSafetyNumberFingerprint(
2011 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
2013 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
2014 account
.getSelfAddress(),
2015 getIdentityKeyPair().getPublicKey(),
2021 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2022 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2024 return resolveSignalServiceAddress(address
);
2028 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2029 if (address
.matches(account
.getSelfAddress())) {
2030 return account
.getSelfAddress();
2033 return account
.getRecipientStore().resolveServiceAddress(address
);
2036 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2037 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2040 private String
canonicalizePhoneNumber(final String number
) throws InvalidNumberException
{
2041 return PhoneNumberFormatter
.formatNumber(number
, account
.getUsername());
2044 private RecipientId
resolveRecipient(final String identifier
) {
2045 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2047 return resolveRecipient(address
);
2050 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) {
2051 final SignalServiceAddress address
;
2052 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
2053 address
= new SignalServiceAddress(((RecipientIdentifier
.Uuid
) recipient
).uuid
, null);
2055 address
= new SignalServiceAddress(null, ((RecipientIdentifier
.Number
) recipient
).number
);
2058 return resolveRecipient(address
);
2061 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2062 return account
.getRecipientStore().resolveRecipient(address
);
2065 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2066 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2069 private void enqueueJob(Job job
) {
2070 var context
= new Context(account
,
2071 dependencies
.getAccountManager(),
2072 dependencies
.getMessageReceiver(),
2078 public void close() throws IOException
{
2082 void close(boolean closeAccount
) throws IOException
{
2083 executor
.shutdown();
2085 dependencies
.getSignalWebSocket().disconnect();
2087 if (closeAccount
&& account
!= null) {
2093 public interface ReceiveMessageHandler
{
2095 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);