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
.PhoneNumberSharingMode
;
6 import org
.asamk
.signal
.manager
.api
.Profile
;
7 import org
.asamk
.signal
.manager
.api
.TrustLevel
;
8 import org
.asamk
.signal
.manager
.internal
.SignalDependencies
;
9 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
10 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
11 import org
.signal
.libsignal
.protocol
.IdentityKey
;
12 import org
.signal
.libsignal
.protocol
.InvalidKeyException
;
13 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
14 import org
.signal
.libsignal
.zkgroup
.groups
.GroupMasterKey
;
15 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
16 import org
.slf4j
.Logger
;
17 import org
.slf4j
.LoggerFactory
;
18 import org
.whispersystems
.signalservice
.api
.storage
.SignalAccountRecord
;
19 import org
.whispersystems
.signalservice
.api
.storage
.SignalStorageManifest
;
20 import org
.whispersystems
.signalservice
.api
.storage
.SignalStorageRecord
;
21 import org
.whispersystems
.signalservice
.api
.storage
.StorageId
;
22 import org
.whispersystems
.signalservice
.internal
.storage
.protos
.AccountRecord
;
23 import org
.whispersystems
.signalservice
.internal
.storage
.protos
.ManifestRecord
;
25 import java
.io
.IOException
;
26 import java
.util
.ArrayList
;
27 import java
.util
.Collection
;
28 import java
.util
.Collections
;
29 import java
.util
.List
;
30 import java
.util
.Optional
;
31 import java
.util
.stream
.Collectors
;
33 public class StorageHelper
{
35 private final static Logger logger
= LoggerFactory
.getLogger(StorageHelper
.class);
37 private final SignalAccount account
;
38 private final SignalDependencies dependencies
;
39 private final Context context
;
41 public StorageHelper(final Context context
) {
42 this.account
= context
.getAccount();
43 this.dependencies
= context
.getDependencies();
44 this.context
= context
;
47 public void readDataFromStorage() throws IOException
{
48 final var storageKey
= account
.getOrCreateStorageKey();
49 if (storageKey
== null) {
50 logger
.debug("Storage key unknown, requesting from primary device.");
51 context
.getSyncHelper().requestSyncKeys();
55 logger
.debug("Reading data from remote storage");
56 Optional
<SignalStorageManifest
> manifest
;
58 manifest
= dependencies
.getAccountManager()
59 .getStorageManifestIfDifferentVersion(storageKey
, account
.getStorageManifestVersion());
60 } catch (InvalidKeyException e
) {
61 logger
.warn("Manifest couldn't be decrypted, ignoring.");
65 if (manifest
.isEmpty()) {
66 logger
.debug("Manifest is up to date, does not exist or couldn't be decrypted, ignoring.");
70 logger
.trace("Remote storage manifest has {} records", manifest
.get().getStorageIds().size());
71 final var storageIds
= manifest
.get()
74 .filter(id
-> !id
.isUnknown())
75 .collect(Collectors
.toSet());
77 Optional
<SignalStorageManifest
> localManifest
= account
.getStorageManifest();
78 localManifest
.ifPresent(m
-> m
.getStorageIds().forEach(storageIds
::remove
));
80 logger
.trace("Reading {} new records", manifest
.get().getStorageIds().size());
81 for (final var record : getSignalStorageRecords(storageIds
)) {
82 logger
.debug("Reading record of type {}", record.getType());
83 if (record.getType() == ManifestRecord
.Identifier
.Type
.ACCOUNT_VALUE
) {
84 readAccountRecord(record);
85 } else if (record.getType() == ManifestRecord
.Identifier
.Type
.GROUPV2_VALUE
) {
86 readGroupV2Record(record);
87 } else if (record.getType() == ManifestRecord
.Identifier
.Type
.GROUPV1_VALUE
) {
88 readGroupV1Record(record);
89 } else if (record.getType() == ManifestRecord
.Identifier
.Type
.CONTACT_VALUE
) {
90 readContactRecord(record);
93 account
.setStorageManifestVersion(manifest
.get().getVersion());
94 account
.setStorageManifest(manifest
.get());
95 logger
.debug("Done reading data from remote storage");
98 private void readContactRecord(final SignalStorageRecord
record) {
99 if (record == null || record.getContact().isEmpty()) {
103 final var contactRecord
= record.getContact().get();
104 final var aci
= contactRecord
.getAci().orElse(null);
105 final var pni
= contactRecord
.getPni().orElse(null);
106 if (contactRecord
.getNumber().isEmpty() && aci
== null && pni
== null) {
109 final var address
= new RecipientAddress(aci
, pni
, contactRecord
.getNumber().orElse(null));
110 var recipientId
= account
.getRecipientResolver().resolveRecipient(address
);
111 if (aci
!= null && contactRecord
.getUsername().isPresent()) {
112 recipientId
= account
.getRecipientTrustedResolver()
113 .resolveRecipientTrusted(aci
, contactRecord
.getUsername().get());
116 final var contact
= account
.getContactStore().getContact(recipientId
);
117 final var blocked
= contact
!= null && contact
.isBlocked();
118 final var profileShared
= contact
!= null && contact
.isProfileSharingEnabled();
119 final var archived
= contact
!= null && contact
.isArchived();
120 final var contactGivenName
= contact
== null ?
null : contact
.getGivenName();
121 final var contactFamilyName
= contact
== null ?
null : contact
.getFamilyName();
122 if (blocked
!= contactRecord
.isBlocked()
123 || profileShared
!= contactRecord
.isProfileSharingEnabled()
124 || archived
!= contactRecord
.isArchived()
126 contactRecord
.getSystemGivenName().isPresent() && !contactRecord
.getSystemGivenName()
128 .equals(contactGivenName
)
131 contactRecord
.getSystemFamilyName().isPresent() && !contactRecord
.getSystemFamilyName()
133 .equals(contactFamilyName
)
135 logger
.debug("Storing new or updated contact {}", recipientId
);
136 final var contactBuilder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
137 final var newContact
= contactBuilder
.withBlocked(contactRecord
.isBlocked())
138 .withProfileSharingEnabled(contactRecord
.isProfileSharingEnabled())
139 .withArchived(contactRecord
.isArchived());
140 if (contactRecord
.getSystemGivenName().isPresent() || contactRecord
.getSystemFamilyName().isPresent()) {
141 newContact
.withGivenName(contactRecord
.getSystemGivenName().orElse(null))
142 .withFamilyName(contactRecord
.getSystemFamilyName().orElse(null));
144 account
.getContactStore().storeContact(recipientId
, newContact
.build());
147 final var profile
= account
.getProfileStore().getProfile(recipientId
);
148 final var profileGivenName
= profile
== null ?
null : profile
.getGivenName();
149 final var profileFamilyName
= profile
== null ?
null : profile
.getFamilyName();
151 contactRecord
.getProfileGivenName().isPresent() && !contactRecord
.getProfileGivenName()
153 .equals(profileGivenName
)
155 contactRecord
.getProfileFamilyName().isPresent() && !contactRecord
.getProfileFamilyName()
157 .equals(profileFamilyName
)
159 final var profileBuilder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
160 final var newProfile
= profileBuilder
.withGivenName(contactRecord
.getProfileGivenName().orElse(null))
161 .withFamilyName(contactRecord
.getProfileFamilyName().orElse(null))
163 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
165 if (contactRecord
.getProfileKey().isPresent()) {
167 logger
.trace("Storing profile key {}", recipientId
);
168 final var profileKey
= new ProfileKey(contactRecord
.getProfileKey().get());
169 account
.getProfileStore().storeProfileKey(recipientId
, profileKey
);
170 } catch (InvalidInputException e
) {
171 logger
.warn("Received invalid contact profile key from storage");
174 if (contactRecord
.getIdentityKey().isPresent() && aci
!= null) {
176 logger
.trace("Storing identity key {}", recipientId
);
177 final var identityKey
= new IdentityKey(contactRecord
.getIdentityKey().get());
178 account
.getIdentityKeyStore().saveIdentity(aci
, identityKey
);
180 final var trustLevel
= TrustLevel
.fromIdentityState(contactRecord
.getIdentityState());
181 if (trustLevel
!= null) {
182 account
.getIdentityKeyStore().setIdentityTrustLevel(aci
, identityKey
, trustLevel
);
184 } catch (InvalidKeyException e
) {
185 logger
.warn("Received invalid contact identity key from storage");
190 private void readGroupV1Record(final SignalStorageRecord
record) {
191 if (record == null || record.getGroupV1().isEmpty()) {
195 final var groupV1Record
= record.getGroupV1().get();
196 final var groupIdV1
= GroupId
.v1(groupV1Record
.getGroupId());
198 var group
= account
.getGroupStore().getGroup(groupIdV1
);
201 context
.getGroupHelper().sendGroupInfoRequest(groupIdV1
, account
.getSelfRecipientId());
202 } catch (Throwable e
) {
203 logger
.warn("Failed to send group request", e
);
205 group
= account
.getGroupStore().getOrCreateGroupV1(groupIdV1
);
207 if (group
!= null && group
.isBlocked() != groupV1Record
.isBlocked()) {
208 group
.setBlocked(groupV1Record
.isBlocked());
209 account
.getGroupStore().updateGroup(group
);
213 private void readGroupV2Record(final SignalStorageRecord
record) {
214 if (record == null || record.getGroupV2().isEmpty()) {
218 final var groupV2Record
= record.getGroupV2().get();
219 if (groupV2Record
.isArchived()) {
223 final GroupMasterKey groupMasterKey
;
225 groupMasterKey
= new GroupMasterKey(groupV2Record
.getMasterKeyBytes());
226 } catch (InvalidInputException e
) {
227 logger
.warn("Received invalid group master key from storage");
231 final var group
= context
.getGroupHelper().getOrMigrateGroup(groupMasterKey
, 0, null);
232 if (group
.isBlocked() != groupV2Record
.isBlocked()) {
233 group
.setBlocked(groupV2Record
.isBlocked());
234 account
.getGroupStore().updateGroup(group
);
238 private void readAccountRecord(final SignalStorageRecord
record) throws IOException
{
239 if (record == null) {
240 logger
.warn("Could not find account record, even though we had an ID, ignoring.");
244 SignalAccountRecord accountRecord
= record.getAccount().orElse(null);
245 if (accountRecord
== null) {
246 logger
.warn("The storage record didn't actually have an account, ignoring.");
250 if (!accountRecord
.getE164().equals(account
.getNumber())) {
251 context
.getAccountHelper().checkWhoAmiI();
254 account
.getConfigurationStore().setReadReceipts(accountRecord
.isReadReceiptsEnabled());
255 account
.getConfigurationStore().setTypingIndicators(accountRecord
.isTypingIndicatorsEnabled());
256 account
.getConfigurationStore()
257 .setUnidentifiedDeliveryIndicators(accountRecord
.isSealedSenderIndicatorsEnabled());
258 account
.getConfigurationStore().setLinkPreviews(accountRecord
.isLinkPreviewsEnabled());
259 if (accountRecord
.getPhoneNumberSharingMode() != AccountRecord
.PhoneNumberSharingMode
.UNRECOGNIZED
) {
260 account
.getConfigurationStore()
261 .setPhoneNumberSharingMode(switch (accountRecord
.getPhoneNumberSharingMode()) {
262 case EVERYBODY
-> PhoneNumberSharingMode
.EVERYBODY
;
263 case NOBODY
-> PhoneNumberSharingMode
.NOBODY
;
264 default -> PhoneNumberSharingMode
.CONTACTS
;
267 account
.getConfigurationStore().setPhoneNumberUnlisted(accountRecord
.isPhoneNumberUnlisted());
268 account
.setUsername(accountRecord
.getUsername());
270 if (accountRecord
.getProfileKey().isPresent()) {
271 ProfileKey profileKey
;
273 profileKey
= new ProfileKey(accountRecord
.getProfileKey().get());
274 } catch (InvalidInputException e
) {
275 logger
.warn("Received invalid profile key from storage");
278 if (profileKey
!= null) {
279 account
.setProfileKey(profileKey
);
280 final var avatarPath
= accountRecord
.getAvatarUrlPath().orElse(null);
281 context
.getProfileHelper().downloadProfileAvatar(account
.getSelfRecipientId(), avatarPath
, profileKey
);
285 context
.getProfileHelper()
288 accountRecord
.getGivenName().orElse(null),
289 accountRecord
.getFamilyName().orElse(null),
296 private SignalStorageRecord
getSignalStorageRecord(final StorageId accountId
) throws IOException
{
297 List
<SignalStorageRecord
> records
;
299 records
= dependencies
.getAccountManager()
300 .readStorageRecords(account
.getStorageKey(), Collections
.singletonList(accountId
));
301 } catch (InvalidKeyException e
) {
302 logger
.warn("Failed to read storage records, ignoring.");
305 return records
.size() > 0 ? records
.get(0) : null;
308 private List
<SignalStorageRecord
> getSignalStorageRecords(final Collection
<StorageId
> storageIds
) throws IOException
{
309 List
<SignalStorageRecord
> records
;
311 records
= dependencies
.getAccountManager()
312 .readStorageRecords(account
.getStorageKey(), new ArrayList
<>(storageIds
));
313 } catch (InvalidKeyException e
) {
314 logger
.warn("Failed to read storage records, ignoring.");