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
.AttachmentUtils
;
13 import org
.asamk
.signal
.manager
.util
.IOUtils
;
14 import org
.asamk
.signal
.manager
.util
.MimeUtils
;
15 import org
.jetbrains
.annotations
.NotNull
;
16 import org
.signal
.libsignal
.protocol
.IdentityKey
;
17 import org
.slf4j
.Logger
;
18 import org
.slf4j
.LoggerFactory
;
19 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
20 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
21 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
22 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
23 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ConfigurationMessage
;
24 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
25 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
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
.RequestMessage
;
34 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
35 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
36 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
37 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
38 import org
.whispersystems
.signalservice
.internal
.push
.SyncMessage
;
40 import java
.io
.FileInputStream
;
41 import java
.io
.FileOutputStream
;
42 import java
.io
.IOException
;
43 import java
.io
.InputStream
;
44 import java
.io
.OutputStream
;
45 import java
.nio
.file
.Files
;
46 import java
.util
.ArrayList
;
47 import java
.util
.List
;
48 import java
.util
.Optional
;
49 import java
.util
.stream
.Collectors
;
50 import java
.util
.stream
.Stream
;
52 public class SyncHelper
{
54 private static final Logger logger
= LoggerFactory
.getLogger(SyncHelper
.class);
56 private final Context context
;
57 private final SignalAccount account
;
59 public SyncHelper(final Context context
) {
60 this.context
= context
;
61 this.account
= context
.getAccount();
64 public void requestAllSyncData() {
65 requestSyncData(SyncMessage
.Request
.Type
.GROUPS
);
66 requestSyncData(SyncMessage
.Request
.Type
.CONTACTS
);
67 requestSyncData(SyncMessage
.Request
.Type
.BLOCKED
);
68 requestSyncData(SyncMessage
.Request
.Type
.CONFIGURATION
);
70 requestSyncPniIdentity();
73 public void requestSyncKeys() {
74 requestSyncData(SyncMessage
.Request
.Type
.KEYS
);
77 public void requestSyncPniIdentity() {
78 requestSyncData(SyncMessage
.Request
.Type
.PNI_IDENTITY
);
81 public SendMessageResult
sendSyncFetchProfileMessage() {
82 return context
.getSendHelper()
83 .sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
86 public void sendSyncFetchStorageMessage() {
87 context
.getSendHelper()
88 .sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.STORAGE_MANIFEST
));
91 public void sendGroups() throws IOException
{
92 var groupsFile
= IOUtils
.createTempFile();
95 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
96 var out
= new DeviceGroupsOutputStream(fos
);
97 for (var record : account
.getGroupStore().getGroups()) {
98 if (record instanceof GroupInfoV1 groupInfo
) {
99 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
100 Optional
.ofNullable(groupInfo
.name
),
101 groupInfo
.getMembers()
103 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
105 context
.getGroupHelper().createGroupAvatarAttachment(groupInfo
.getGroupId()),
106 groupInfo
.isMember(account
.getSelfRecipientId()),
107 Optional
.of(groupInfo
.messageExpirationTime
),
108 Optional
.ofNullable(groupInfo
.color
),
111 groupInfo
.archived
));
116 if (groupsFile
.exists() && groupsFile
.length() > 0) {
117 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
118 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
119 .withStream(groupsFileStream
)
120 .withContentType(MimeUtils
.OCTET_STREAM
)
121 .withLength(groupsFile
.length())
124 context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
129 Files
.delete(groupsFile
.toPath());
130 } catch (IOException e
) {
131 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
136 public void sendContacts() throws IOException
{
137 var contactsFile
= IOUtils
.createTempFile();
140 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
141 var out
= new DeviceContactsOutputStream(fos
);
142 for (var contactPair
: account
.getContactStore().getContacts()) {
143 final var recipientId
= contactPair
.first();
144 final var contact
= contactPair
.second();
145 final var address
= account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
);
147 out
.write(getDeviceContact(address
, recipientId
, contact
));
150 if (account
.getProfileKey() != null) {
151 // Send our own profile key as well
152 final var address
= account
.getSelfRecipientAddress();
153 final var recipientId
= account
.getSelfRecipientId();
154 final var contact
= account
.getContactStore().getContact(recipientId
);
155 out
.write(getDeviceContact(address
, recipientId
, contact
));
159 if (contactsFile
.exists() && contactsFile
.length() > 0) {
160 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
161 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
162 .withStream(contactsFileStream
)
163 .withContentType(MimeUtils
.OCTET_STREAM
)
164 .withLength(contactsFile
.length())
167 context
.getSendHelper()
168 .sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
,
174 Files
.delete(contactsFile
.toPath());
175 } catch (IOException e
) {
176 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
182 private DeviceContact
getDeviceContact(
183 final RecipientAddress address
, final RecipientId recipientId
, final Contact contact
184 ) throws IOException
{
185 var currentIdentity
= address
.serviceId().isEmpty()
187 : account
.getIdentityKeyStore().getIdentityInfo(address
.serviceId().get());
188 VerifiedMessage verifiedMessage
= null;
189 if (currentIdentity
!= null) {
190 verifiedMessage
= new VerifiedMessage(address
.toSignalServiceAddress(),
191 currentIdentity
.getIdentityKey(),
192 currentIdentity
.getTrustLevel().toVerifiedState(),
193 currentIdentity
.getDateAddedTimestamp());
196 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
197 return new DeviceContact(address
.aci(),
199 Optional
.ofNullable(contact
== null ?
null : contact
.getName()),
200 createContactAvatarAttachment(address
),
201 Optional
.ofNullable(contact
== null ?
null : contact
.color()),
202 Optional
.ofNullable(verifiedMessage
),
203 Optional
.ofNullable(profileKey
),
204 contact
!= null && contact
.isBlocked(),
205 Optional
.ofNullable(contact
== null ?
null : contact
.messageExpirationTime()),
207 contact
!= null && contact
.isArchived());
210 public SendMessageResult
sendBlockedList() {
211 var addresses
= new ArrayList
<SignalServiceAddress
>();
212 for (var record : account
.getContactStore().getContacts()) {
213 if (record.second().isBlocked()) {
214 addresses
.add(context
.getRecipientHelper().resolveSignalServiceAddress(record.first()));
217 var groupIds
= new ArrayList
<byte[]>();
218 for (var record : account
.getGroupStore().getGroups()) {
219 if (record.isBlocked()) {
220 groupIds
.add(record.getGroupId().serialize());
223 return context
.getSendHelper()
224 .sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
227 public SendMessageResult
sendVerifiedMessage(
228 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
230 var verifiedMessage
= new VerifiedMessage(destination
,
232 trustLevel
.toVerifiedState(),
233 System
.currentTimeMillis());
234 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
237 public SendMessageResult
sendKeysMessage() {
238 var keysMessage
= new KeysMessage(Optional
.ofNullable(account
.getOrCreateStorageKey()),
239 Optional
.ofNullable(account
.getOrCreatePinMasterKey()));
240 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forKeys(keysMessage
));
243 public SendMessageResult
sendStickerOperationsMessage(
244 List
<StickerPack
> installStickers
, List
<StickerPack
> removeStickers
246 var installStickerMessages
= installStickers
.stream().map(s
-> getStickerPackOperationMessage(s
, true));
247 var removeStickerMessages
= removeStickers
.stream().map(s
-> getStickerPackOperationMessage(s
, false));
248 var stickerMessages
= Stream
.concat(installStickerMessages
, removeStickerMessages
).toList();
249 return context
.getSendHelper()
250 .sendSyncMessage(SignalServiceSyncMessage
.forStickerPackOperations(stickerMessages
));
253 private static StickerPackOperationMessage
getStickerPackOperationMessage(
254 final StickerPack s
, final boolean installed
256 return new StickerPackOperationMessage(s
.packId().serialize(),
258 installed ? StickerPackOperationMessage
.Type
.INSTALL
: StickerPackOperationMessage
.Type
.REMOVE
);
261 public SendMessageResult
sendConfigurationMessage() {
262 final var config
= account
.getConfigurationStore();
263 var configurationMessage
= new ConfigurationMessage(Optional
.ofNullable(config
.getReadReceipts()),
264 Optional
.ofNullable(config
.getUnidentifiedDeliveryIndicators()),
265 Optional
.ofNullable(config
.getTypingIndicators()),
266 Optional
.ofNullable(config
.getLinkPreviews()));
267 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forConfiguration(configurationMessage
));
270 public void handleSyncDeviceGroups(final InputStream input
) {
271 final var s
= new DeviceGroupsInputStream(input
);
276 } catch (IOException e
) {
277 logger
.warn("Sync groups contained invalid group, ignoring: {}", e
.getMessage());
283 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
284 if (syncGroup
!= null) {
285 if (g
.getName().isPresent()) {
286 syncGroup
.name
= g
.getName().get();
288 syncGroup
.addMembers(g
.getMembers()
290 .map(account
.getRecipientResolver()::resolveRecipient
)
291 .collect(Collectors
.toSet()));
293 syncGroup
.removeMember(account
.getSelfRecipientId());
295 // Add ourself to the member set as it's marked as active
296 syncGroup
.addMembers(List
.of(account
.getSelfRecipientId()));
298 syncGroup
.blocked
= g
.isBlocked();
299 if (g
.getColor().isPresent()) {
300 syncGroup
.color
= g
.getColor().get();
303 if (g
.getAvatar().isPresent()) {
304 context
.getGroupHelper().downloadGroupAvatar(syncGroup
.getGroupId(), g
.getAvatar().get());
306 syncGroup
.archived
= g
.isArchived();
307 account
.getGroupStore().updateGroup(syncGroup
);
312 public void handleSyncDeviceContacts(final InputStream input
) throws IOException
{
313 final var s
= new DeviceContactsInputStream(input
);
318 } catch (IOException e
) {
319 if (e
.getMessage() != null && e
.getMessage().contains("Missing contact address!")) {
320 logger
.warn("Sync contacts contained invalid contact, ignoring: {}", e
.getMessage());
326 if (c
== null || (c
.getAci().isEmpty() && c
.getE164().isEmpty())) {
329 final var address
= new RecipientAddress(c
.getAci(), Optional
.empty(), c
.getE164(), Optional
.empty());
330 if (address
.matches(account
.getSelfRecipientAddress()) && c
.getProfileKey().isPresent()) {
331 account
.setProfileKey(c
.getProfileKey().get());
333 final var recipientId
= account
.getRecipientTrustedResolver().resolveRecipientTrusted(address
);
334 var contact
= account
.getContactStore().getContact(recipientId
);
335 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
336 if (c
.getName().isPresent() && (
338 contact
.givenName() == null && contact
.familyName() == null
341 builder
.withGivenName(c
.getName().get());
342 builder
.withFamilyName(null);
344 if (c
.getColor().isPresent()) {
345 builder
.withColor(c
.getColor().get());
347 if (c
.getProfileKey().isPresent()) {
348 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
350 if (c
.getVerified().isPresent()) {
351 final var verifiedMessage
= c
.getVerified().get();
352 account
.getIdentityKeyStore()
353 .setIdentityTrustLevel(verifiedMessage
.getDestination().getServiceId(),
354 verifiedMessage
.getIdentityKey(),
355 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
357 if (c
.getExpirationTimer().isPresent()) {
358 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
360 builder
.withIsBlocked(c
.isBlocked());
361 builder
.withIsArchived(c
.isArchived());
362 account
.getContactStore().storeContact(recipientId
, builder
.build());
364 if (c
.getAvatar().isPresent()) {
365 downloadContactAvatar(c
.getAvatar().get(), address
);
370 public SendMessageResult
sendMessageRequestResponse(
371 final MessageRequestResponse
.Type type
, final GroupId groupId
373 final var response
= MessageRequestResponseMessage
.forGroup(groupId
.serialize(), localToRemoteType(type
));
374 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forMessageRequestResponse(response
));
377 public SendMessageResult
sendMessageRequestResponse(
378 final MessageRequestResponse
.Type type
, final RecipientId recipientId
380 final var address
= account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
);
381 if (address
.serviceId().isEmpty()) {
384 context
.getContactHelper()
385 .setContactProfileSharing(recipientId
,
386 type
== MessageRequestResponse
.Type
.ACCEPT
387 || type
== MessageRequestResponse
.Type
.UNBLOCK_AND_ACCEPT
);
388 final var response
= MessageRequestResponseMessage
.forIndividual(address
.serviceId().get(),
389 localToRemoteType(type
));
390 return context
.getSendHelper().sendSyncMessage(SignalServiceSyncMessage
.forMessageRequestResponse(response
));
393 private SendMessageResult
requestSyncData(final SyncMessage
.Request
.Type type
) {
394 var r
= new SyncMessage
.Request
.Builder().type(type
).build();
395 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
396 return context
.getSendHelper().sendSyncMessage(message
);
399 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(RecipientAddress address
) throws IOException
{
400 final var streamDetails
= context
.getAvatarStore().retrieveContactAvatar(address
);
401 if (streamDetails
== null) {
402 return Optional
.empty();
405 return Optional
.of(AttachmentUtils
.createAttachmentStream(streamDetails
, Optional
.empty()));
408 private void downloadContactAvatar(SignalServiceAttachment avatar
, RecipientAddress address
) {
410 context
.getAvatarStore()
411 .storeContactAvatar(address
,
412 outputStream
-> context
.getAttachmentHelper().retrieveAttachment(avatar
, outputStream
));
413 } catch (IOException e
) {
414 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
418 private MessageRequestResponseMessage
.Type
localToRemoteType(final MessageRequestResponse
.Type type
) {
419 return switch (type
) {
420 case UNKNOWN
-> MessageRequestResponseMessage
.Type
.UNKNOWN
;
421 case ACCEPT
-> MessageRequestResponseMessage
.Type
.ACCEPT
;
422 case DELETE
-> MessageRequestResponseMessage
.Type
.DELETE
;
423 case BLOCK
-> MessageRequestResponseMessage
.Type
.BLOCK
;
424 case BLOCK_AND_DELETE
-> MessageRequestResponseMessage
.Type
.BLOCK_AND_DELETE
;
425 case UNBLOCK_AND_ACCEPT
-> MessageRequestResponseMessage
.Type
.UNBLOCK_AND_ACCEPT
;
426 case SPAM
-> MessageRequestResponseMessage
.Type
.SPAM
;
427 case BLOCK_AND_SPAM
-> MessageRequestResponseMessage
.Type
.BLOCK_AND_SPAM
;