1 package org
.asamk
.signal
.manager
.helper
;
3 import org
.asamk
.signal
.manager
.api
.Contact
;
4 import org
.asamk
.signal
.manager
.api
.GroupId
;
5 import org
.asamk
.signal
.manager
.api
.MessageEnvelope
.Sync
.MessageRequestResponse
;
6 import org
.asamk
.signal
.manager
.api
.TrustLevel
;
7 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
8 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
9 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
10 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
11 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPack
;
12 import org
.asamk
.signal
.manager
.util
.IOUtils
;
13 import org
.asamk
.signal
.manager
.util
.MimeUtils
;
14 import org
.jetbrains
.annotations
.NotNull
;
15 import org
.signal
.libsignal
.protocol
.IdentityKey
;
16 import org
.slf4j
.Logger
;
17 import org
.slf4j
.LoggerFactory
;
18 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
19 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
20 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
21 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
22 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ConfigurationMessage
;
23 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
24 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
25 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactAvatar
;
26 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
27 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
28 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
29 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
30 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
31 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.KeysMessage
;
32 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.MessageRequestResponseMessage
;
33 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ReadMessage
;
34 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
35 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
36 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
37 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
38 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ViewedMessage
;
39 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
40 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
41 import org
.whispersystems
.signalservice
.internal
.push
.SyncMessage
;
43 import java
.io
.FileInputStream
;
44 import java
.io
.FileOutputStream
;
45 import java
.io
.IOException
;
46 import java
.io
.InputStream
;
47 import java
.io
.OutputStream
;
48 import java
.nio
.file
.Files
;
49 import java
.util
.ArrayList
;
50 import java
.util
.List
;
51 import java
.util
.Optional
;
52 import java
.util
.stream
.Collectors
;
53 import java
.util
.stream
.Stream
;
55 public class SyncHelper
{
57 private static final Logger logger
= LoggerFactory
.getLogger(SyncHelper
.class);
59 private final Context context
;
60 private final SignalAccount account
;
62 public SyncHelper(final Context context
) {
63 this.context
= context
;
64 this.account
= context
.getAccount();
67 public void requestAllSyncData() {
68 requestSyncData(SyncMessage
.Request
.Type
.GROUPS
);
69 requestSyncData(SyncMessage
.Request
.Type
.CONTACTS
);
70 requestSyncData(SyncMessage
.Request
.Type
.BLOCKED
);
71 requestSyncData(SyncMessage
.Request
.Type
.CONFIGURATION
);
73 requestSyncPniIdentity();
76 public void requestSyncKeys() {
77 requestSyncData(SyncMessage
.Request
.Type
.KEYS
);
80 public void requestSyncPniIdentity() {
81 requestSyncData(SyncMessage
.Request
.Type
.PNI_IDENTITY
);
84 public SendMessageResult
sendSyncFetchProfileMessage() {
85 return context
.getSendHelper()
86 .sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
89 public void sendSyncFetchStorageMessage() {
90 context
.getSendHelper()
91 .sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.STORAGE_MANIFEST
));
94 public void sendSyncReceiptMessage(ServiceId sender
, SignalServiceReceiptMessage receiptMessage
) {
95 if (receiptMessage
.isReadReceipt()) {
96 final var readMessages
= receiptMessage
.getTimestamps()
98 .map(t
-> new ReadMessage(sender
, t
))
100 context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forRead(readMessages
));
101 } else if (receiptMessage
.isViewedReceipt()) {
102 final var viewedMessages
= receiptMessage
.getTimestamps()
104 .map(t
-> new ViewedMessage(sender
, t
))
106 context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forViewed(viewedMessages
));
110 public void sendGroups() throws IOException
{
111 var groupsFile
= IOUtils
.createTempFile();
114 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
115 var out
= new DeviceGroupsOutputStream(fos
);
116 for (var record : account
.getGroupStore().getGroups()) {
117 if (record instanceof GroupInfoV1 groupInfo
) {
118 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
119 Optional
.ofNullable(groupInfo
.name
),
120 groupInfo
.getMembers()
122 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
124 context
.getGroupHelper().createGroupAvatarAttachment(groupInfo
.getGroupId()),
125 groupInfo
.isMember(account
.getSelfRecipientId()),
126 Optional
.of(groupInfo
.messageExpirationTime
),
127 Optional
.ofNullable(groupInfo
.color
),
130 groupInfo
.archived
));
135 if (groupsFile
.exists() && groupsFile
.length() > 0) {
136 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
137 final var uploadSpec
= context
.getDependencies().getMessageSender().getResumableUploadSpec();
138 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
139 .withStream(groupsFileStream
)
140 .withContentType(MimeUtils
.OCTET_STREAM
)
141 .withLength(groupsFile
.length())
142 .withResumableUploadSpec(uploadSpec
)
145 context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
150 Files
.delete(groupsFile
.toPath());
151 } catch (IOException e
) {
152 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
157 public void sendContacts() throws IOException
{
158 var contactsFile
= IOUtils
.createTempFile();
161 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
162 var out
= new DeviceContactsOutputStream(fos
);
163 for (var contactPair
: account
.getContactStore().getContacts()) {
164 final var recipientId
= contactPair
.first();
165 final var contact
= contactPair
.second();
166 final var address
= account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
);
168 final var deviceContact
= getDeviceContact(address
, recipientId
, contact
);
169 out
.write(deviceContact
);
170 deviceContact
.getAvatar().ifPresent(a
-> {
172 a
.getInputStream().close();
173 } catch (IOException ignored
) {
178 if (account
.getProfileKey() != null) {
179 // Send our own profile key as well
180 final var address
= account
.getSelfRecipientAddress();
181 final var recipientId
= account
.getSelfRecipientId();
182 final var contact
= account
.getContactStore().getContact(recipientId
);
183 final var deviceContact
= getDeviceContact(address
, recipientId
, contact
);
184 out
.write(deviceContact
);
185 deviceContact
.getAvatar().ifPresent(a
-> {
187 a
.getInputStream().close();
188 } catch (IOException ignored
) {
194 if (contactsFile
.exists() && contactsFile
.length() > 0) {
195 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
196 final var uploadSpec
= context
.getDependencies().getMessageSender().getResumableUploadSpec();
197 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
198 .withStream(contactsFileStream
)
199 .withContentType(MimeUtils
.OCTET_STREAM
)
200 .withLength(contactsFile
.length())
201 .withResumableUploadSpec(uploadSpec
)
204 context
.getSendHelper()
205 .sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
,
211 Files
.delete(contactsFile
.toPath());
212 } catch (IOException e
) {
213 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
219 private DeviceContact
getDeviceContact(
220 final RecipientAddress address
, final RecipientId recipientId
, final Contact contact
221 ) throws IOException
{
222 var currentIdentity
= address
.serviceId().isEmpty()
224 : account
.getIdentityKeyStore().getIdentityInfo(address
.serviceId().get());
225 VerifiedMessage verifiedMessage
= null;
226 if (currentIdentity
!= null) {
227 verifiedMessage
= new VerifiedMessage(address
.toSignalServiceAddress(),
228 currentIdentity
.getIdentityKey(),
229 currentIdentity
.getTrustLevel().toVerifiedState(),
230 currentIdentity
.getDateAddedTimestamp());
233 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
234 return new DeviceContact(address
.aci(),
236 Optional
.ofNullable(contact
== null ?
null : contact
.getName()),
237 createContactAvatarAttachment(address
),
238 Optional
.ofNullable(contact
== null ?
null : contact
.color()),
239 Optional
.ofNullable(verifiedMessage
),
240 Optional
.ofNullable(profileKey
),
241 Optional
.ofNullable(contact
== null ?
null : contact
.messageExpirationTime()),
242 Optional
.ofNullable(contact
== null ?
null : contact
.messageExpirationTimeVersion()),
244 contact
!= null && contact
.isArchived());
247 public SendMessageResult
sendBlockedList() {
248 var addresses
= new ArrayList
<SignalServiceAddress
>();
249 for (var record : account
.getContactStore().getContacts()) {
250 if (record.second().isBlocked()) {
251 addresses
.add(context
.getRecipientHelper().resolveSignalServiceAddress(record.first()));
254 var groupIds
= new ArrayList
<byte[]>();
255 for (var record : account
.getGroupStore().getGroups()) {
256 if (record.isBlocked()) {
257 groupIds
.add(record.getGroupId().serialize());
260 return context
.getSendHelper()
261 .sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
264 public SendMessageResult
sendVerifiedMessage(
265 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
267 var verifiedMessage
= new VerifiedMessage(destination
,
269 trustLevel
.toVerifiedState(),
270 System
.currentTimeMillis());
271 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
274 public SendMessageResult
sendKeysMessage() {
275 var keysMessage
= new KeysMessage(Optional
.ofNullable(account
.getOrCreateStorageKey()),
276 Optional
.ofNullable(account
.getOrCreatePinMasterKey()));
277 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forKeys(keysMessage
));
280 public SendMessageResult
sendStickerOperationsMessage(
281 List
<StickerPack
> installStickers
, List
<StickerPack
> removeStickers
283 var installStickerMessages
= installStickers
.stream().map(s
-> getStickerPackOperationMessage(s
, true));
284 var removeStickerMessages
= removeStickers
.stream().map(s
-> getStickerPackOperationMessage(s
, false));
285 var stickerMessages
= Stream
.concat(installStickerMessages
, removeStickerMessages
).toList();
286 return context
.getSendHelper()
287 .sendSyncMessage(SignalServiceSyncMessage
.forStickerPackOperations(stickerMessages
));
290 private static StickerPackOperationMessage
getStickerPackOperationMessage(
291 final StickerPack s
, final boolean installed
293 return new StickerPackOperationMessage(s
.packId().serialize(),
295 installed ? StickerPackOperationMessage
.Type
.INSTALL
: StickerPackOperationMessage
.Type
.REMOVE
);
298 public SendMessageResult
sendConfigurationMessage() {
299 final var config
= account
.getConfigurationStore();
300 var configurationMessage
= new ConfigurationMessage(Optional
.ofNullable(config
.getReadReceipts()),
301 Optional
.ofNullable(config
.getUnidentifiedDeliveryIndicators()),
302 Optional
.ofNullable(config
.getTypingIndicators()),
303 Optional
.ofNullable(config
.getLinkPreviews()));
304 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forConfiguration(configurationMessage
));
307 public void handleSyncDeviceGroups(final InputStream input
) {
308 final var s
= new DeviceGroupsInputStream(input
);
313 } catch (IOException e
) {
314 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
320 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
321 if (syncGroup
!= null) {
322 if (g
.getName().isPresent()) {
323 syncGroup
.name
= g
.getName().get();
325 syncGroup
.addMembers(g
.getMembers()
327 .map(account
.getRecipientResolver()::resolveRecipient
)
328 .collect(Collectors
.toSet()));
330 syncGroup
.removeMember(account
.getSelfRecipientId());
332 // Add ourself to the member set as it's marked as active
333 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
335 syncGroup
.blocked
= g
.isBlocked();
336 if (g
.getColor().isPresent()) {
337 syncGroup
.color
= g
.getColor().get();
340 if (g
.getAvatar().isPresent()) {
341 context
.getGroupHelper().downloadGroupAvatar(syncGroup
.getGroupId(), g
.getAvatar().get());
343 syncGroup
.archived
= g
.isArchived();
344 account
.getGroupStore().updateGroup(syncGroup
);
349 public void handleSyncDeviceContacts(final InputStream input
) throws IOException
{
350 final var s
= new DeviceContactsInputStream(input
);
355 } catch (IOException e
) {
356 if (e
.getMessage() != null && e
.getMessage().contains("Missing contact address!")) {
357 logger
.warn("Sync contacts contained invalid contact, ignoring: {}", e
.getMessage());
363 if (c
== null || (c
.getAci().isEmpty() && c
.getE164().isEmpty())) {
366 final var address
= new RecipientAddress(c
.getAci(), Optional
.empty(), c
.getE164(), Optional
.empty());
367 if (address
.matches(account
.getSelfRecipientAddress()) && c
.getProfileKey().isPresent()) {
368 account
.setProfileKey(c
.getProfileKey().get());
370 final var recipientId
= account
.getRecipientTrustedResolver().resolveRecipientTrusted(address
);
371 var contact
= account
.getContactStore().getContact(recipientId
);
372 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
373 if (c
.getName().isPresent() && (
375 contact
.givenName() == null && contact
.familyName() == null
378 builder
.withGivenName(c
.getName().get());
379 builder
.withFamilyName(null);
381 if (c
.getColor().isPresent()) {
382 builder
.withColor(c
.getColor().get());
384 if (c
.getProfileKey().isPresent()) {
385 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
387 if (c
.getVerified().isPresent()) {
388 final var verifiedMessage
= c
.getVerified().get();
389 account
.getIdentityKeyStore()
390 .setIdentityTrustLevel(verifiedMessage
.getDestination().getServiceId(),
391 verifiedMessage
.getIdentityKey(),
392 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
394 if (c
.getExpirationTimer().isPresent()) {
395 if (c
.getExpirationTimerVersion().isPresent() && (
396 contact
== null || c
.getExpirationTimerVersion().get() > contact
.messageExpirationTimeVersion()
398 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
399 builder
.withMessageExpirationTimeVersion(c
.getExpirationTimerVersion().get());
402 "[ContactSync] {} was synced with an old expiration timer. Ignoring. Received: {} Current: ${}",
404 c
.getExpirationTimerVersion(),
405 contact
== null ?
1 : contact
.messageExpirationTimeVersion());
408 builder
.withIsArchived(c
.isArchived());
409 account
.getContactStore().storeContact(recipientId
, builder
.build());
411 if (c
.getAvatar().isPresent()) {
412 storeContactAvatar(c
.getAvatar().get(), address
);
417 public SendMessageResult
sendMessageRequestResponse(
418 final MessageRequestResponse
.Type type
, final GroupId groupId
420 final var response
= MessageRequestResponseMessage
.forGroup(groupId
.serialize(), localToRemoteType(type
));
421 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forMessageRequestResponse(response
));
424 public SendMessageResult
sendMessageRequestResponse(
425 final MessageRequestResponse
.Type type
, final RecipientId recipientId
427 final var address
= account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
);
428 if (address
.serviceId().isEmpty()) {
431 context
.getContactHelper()
432 .setContactProfileSharing(recipientId
,
433 type
== MessageRequestResponse
.Type
.ACCEPT
434 || type
== MessageRequestResponse
.Type
.UNBLOCK_AND_ACCEPT
);
435 final var response
= MessageRequestResponseMessage
.forIndividual(address
.serviceId().get(),
436 localToRemoteType(type
));
437 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forMessageRequestResponse(response
));
440 private SendMessageResult
requestSyncData(final SyncMessage
.Request
.Type type
) {
441 var r
= new SyncMessage
.Request
.Builder().type(type
).build();
442 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
443 return context
.getSendHelper().sendSyncMessage(message
);
446 private Optional
<DeviceContactAvatar
> createContactAvatarAttachment(RecipientAddress address
) throws IOException
{
447 final var streamDetails
= context
.getAvatarStore().retrieveContactAvatar(address
);
448 if (streamDetails
== null) {
449 return Optional
.empty();
452 return Optional
.of(new DeviceContactAvatar(streamDetails
.getStream(),
453 streamDetails
.getLength(),
454 streamDetails
.getContentType()));
457 private void storeContactAvatar(DeviceContactAvatar avatar
, RecipientAddress address
) {
459 context
.getAvatarStore()
460 .storeContactAvatar(address
,
461 outputStream
-> IOUtils
.copyStream(avatar
.getInputStream(), outputStream
));
462 } catch (IOException e
) {
463 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
467 private MessageRequestResponseMessage
.Type
localToRemoteType(final MessageRequestResponse
.Type type
) {
468 return switch (type
) {
469 case UNKNOWN
-> MessageRequestResponseMessage
.Type
.UNKNOWN
;
470 case ACCEPT
-> MessageRequestResponseMessage
.Type
.ACCEPT
;
471 case DELETE
-> MessageRequestResponseMessage
.Type
.DELETE
;
472 case BLOCK
-> MessageRequestResponseMessage
.Type
.BLOCK
;
473 case BLOCK_AND_DELETE
-> MessageRequestResponseMessage
.Type
.BLOCK_AND_DELETE
;
474 case UNBLOCK_AND_ACCEPT
-> MessageRequestResponseMessage
.Type
.UNBLOCK_AND_ACCEPT
;
475 case SPAM
-> MessageRequestResponseMessage
.Type
.SPAM
;
476 case BLOCK_AND_SPAM
-> MessageRequestResponseMessage
.Type
.BLOCK_AND_SPAM
;