]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/StorageHelper.java
84d98db28f948e1ef692826d605fd545eba6d939
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / helper / StorageHelper.java
1 package org.asamk.signal.manager.helper;
2
3 import org.asamk.signal.manager.SignalDependencies;
4 import org.asamk.signal.manager.api.PhoneNumberSharingMode;
5 import org.asamk.signal.manager.api.TrustLevel;
6 import org.asamk.signal.manager.groups.GroupId;
7 import org.asamk.signal.manager.storage.SignalAccount;
8 import org.asamk.signal.manager.storage.recipients.Contact;
9 import org.signal.libsignal.protocol.IdentityKey;
10 import org.signal.libsignal.protocol.InvalidKeyException;
11 import org.signal.libsignal.zkgroup.InvalidInputException;
12 import org.signal.libsignal.zkgroup.groups.GroupMasterKey;
13 import org.signal.libsignal.zkgroup.profiles.ProfileKey;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16 import org.whispersystems.signalservice.api.storage.SignalAccountRecord;
17 import org.whispersystems.signalservice.api.storage.SignalStorageManifest;
18 import org.whispersystems.signalservice.api.storage.SignalStorageRecord;
19 import org.whispersystems.signalservice.api.storage.StorageId;
20 import org.whispersystems.signalservice.internal.storage.protos.AccountRecord;
21 import org.whispersystems.signalservice.internal.storage.protos.ManifestRecord;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.stream.Collectors;
30
31 public class StorageHelper {
32
33 private final static Logger logger = LoggerFactory.getLogger(StorageHelper.class);
34
35 private final SignalAccount account;
36 private final SignalDependencies dependencies;
37 private final Context context;
38
39 public StorageHelper(final Context context) {
40 this.account = context.getAccount();
41 this.dependencies = context.getDependencies();
42 this.context = context;
43 }
44
45 public void readDataFromStorage() throws IOException {
46 logger.debug("Reading data from remote storage");
47 Optional<SignalStorageManifest> manifest;
48 try {
49 manifest = dependencies.getAccountManager()
50 .getStorageManifestIfDifferentVersion(account.getStorageKey(), account.getStorageManifestVersion());
51 } catch (InvalidKeyException e) {
52 logger.warn("Manifest couldn't be decrypted, ignoring.");
53 return;
54 }
55
56 if (manifest.isEmpty()) {
57 logger.debug("Manifest is up to date, does not exist or couldn't be decrypted, ignoring.");
58 return;
59 }
60
61 logger.trace("Remote storage manifest has {} records", manifest.get().getStorageIds().size());
62 final var storageIds = manifest.get()
63 .getStorageIds()
64 .stream()
65 .filter(id -> !id.isUnknown())
66 .collect(Collectors.toSet());
67
68 Optional<SignalStorageManifest> localManifest = account.getStorageManifest();
69 localManifest.ifPresent(m -> m.getStorageIds().forEach(storageIds::remove));
70
71 logger.trace("Reading {} new records", manifest.get().getStorageIds().size());
72 for (final var record : getSignalStorageRecords(storageIds)) {
73 logger.debug("Reading record of type {}", record.getType());
74 if (record.getType() == ManifestRecord.Identifier.Type.ACCOUNT_VALUE) {
75 readAccountRecord(record);
76 } else if (record.getType() == ManifestRecord.Identifier.Type.GROUPV2_VALUE) {
77 readGroupV2Record(record);
78 } else if (record.getType() == ManifestRecord.Identifier.Type.GROUPV1_VALUE) {
79 readGroupV1Record(record);
80 } else if (record.getType() == ManifestRecord.Identifier.Type.CONTACT_VALUE) {
81 readContactRecord(record);
82 }
83 }
84 account.setStorageManifestVersion(manifest.get().getVersion());
85 account.setStorageManifest(manifest.get());
86 logger.debug("Done reading data from remote storage");
87 }
88
89 private void readContactRecord(final SignalStorageRecord record) {
90 if (record == null || record.getContact().isEmpty()) {
91 return;
92 }
93
94 final var contactRecord = record.getContact().get();
95 final var address = contactRecord.getAddress();
96
97 final var recipientId = account.getRecipientResolver().resolveRecipient(address);
98 final var contact = account.getContactStore().getContact(recipientId);
99 final var blocked = contact != null && contact.isBlocked();
100 final var profileShared = contact != null && contact.isProfileSharingEnabled();
101 final var givenName = contact == null ? null : contact.getGivenName();
102 final var familyName = contact == null ? null : contact.getFamilyName();
103 if ((contactRecord.getGivenName().isPresent() && !contactRecord.getGivenName().get().equals(givenName)) || (
104 contactRecord.getFamilyName().isPresent() && !contactRecord.getFamilyName().get().equals(familyName)
105 ) || blocked != contactRecord.isBlocked() || profileShared != contactRecord.isProfileSharingEnabled()) {
106 logger.debug("Storing new or updated contact {}", recipientId);
107 final var contactBuilder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
108 final var newContact = contactBuilder.withBlocked(contactRecord.isBlocked())
109 .withGivenName(contactRecord.getGivenName().orElse(null))
110 .withFamilyName(contactRecord.getFamilyName().orElse(null))
111 .withProfileSharingEnabled(contactRecord.isProfileSharingEnabled())
112 .build();
113 account.getContactStore().storeContact(recipientId, newContact);
114 }
115
116 if (contactRecord.getProfileKey().isPresent()) {
117 try {
118 logger.trace("Storing profile key {}", recipientId);
119 final var profileKey = new ProfileKey(contactRecord.getProfileKey().get());
120 account.getProfileStore().storeProfileKey(recipientId, profileKey);
121 } catch (InvalidInputException e) {
122 logger.warn("Received invalid contact profile key from storage");
123 }
124 }
125 if (contactRecord.getIdentityKey().isPresent()) {
126 try {
127 logger.trace("Storing identity key {}", recipientId);
128 final var identityKey = new IdentityKey(contactRecord.getIdentityKey().get());
129 account.getIdentityKeyStore().saveIdentity(recipientId, identityKey);
130
131 final var trustLevel = TrustLevel.fromIdentityState(contactRecord.getIdentityState());
132 if (trustLevel != null) {
133 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identityKey, trustLevel);
134 }
135 } catch (InvalidKeyException e) {
136 logger.warn("Received invalid contact identity key from storage");
137 }
138 }
139 }
140
141 private void readGroupV1Record(final SignalStorageRecord record) {
142 if (record == null || record.getGroupV1().isEmpty()) {
143 return;
144 }
145
146 final var groupV1Record = record.getGroupV1().get();
147 final var groupIdV1 = GroupId.v1(groupV1Record.getGroupId());
148
149 var group = account.getGroupStore().getGroup(groupIdV1);
150 if (group == null) {
151 try {
152 context.getGroupHelper().sendGroupInfoRequest(groupIdV1, account.getSelfRecipientId());
153 } catch (Throwable e) {
154 logger.warn("Failed to send group request", e);
155 }
156 group = account.getGroupStore().getOrCreateGroupV1(groupIdV1);
157 }
158 if (group != null && group.isBlocked() != groupV1Record.isBlocked()) {
159 group.setBlocked(groupV1Record.isBlocked());
160 account.getGroupStore().updateGroup(group);
161 }
162 }
163
164 private void readGroupV2Record(final SignalStorageRecord record) {
165 if (record == null || record.getGroupV2().isEmpty()) {
166 return;
167 }
168
169 final var groupV2Record = record.getGroupV2().get();
170 if (groupV2Record.isArchived()) {
171 return;
172 }
173
174 final GroupMasterKey groupMasterKey;
175 try {
176 groupMasterKey = new GroupMasterKey(groupV2Record.getMasterKeyBytes());
177 } catch (InvalidInputException e) {
178 logger.warn("Received invalid group master key from storage");
179 return;
180 }
181
182 final var group = context.getGroupHelper().getOrMigrateGroup(groupMasterKey, 0, null);
183 if (group.isBlocked() != groupV2Record.isBlocked()) {
184 group.setBlocked(groupV2Record.isBlocked());
185 account.getGroupStore().updateGroup(group);
186 }
187 }
188
189 private void readAccountRecord(final SignalStorageRecord record) throws IOException {
190 if (record == null) {
191 logger.warn("Could not find account record, even though we had an ID, ignoring.");
192 return;
193 }
194
195 SignalAccountRecord accountRecord = record.getAccount().orElse(null);
196 if (accountRecord == null) {
197 logger.warn("The storage record didn't actually have an account, ignoring.");
198 return;
199 }
200
201 if (!accountRecord.getE164().equals(account.getNumber())) {
202 context.getAccountHelper().checkWhoAmiI();
203 }
204
205 account.getConfigurationStore().setReadReceipts(accountRecord.isReadReceiptsEnabled());
206 account.getConfigurationStore().setTypingIndicators(accountRecord.isTypingIndicatorsEnabled());
207 account.getConfigurationStore()
208 .setUnidentifiedDeliveryIndicators(accountRecord.isSealedSenderIndicatorsEnabled());
209 account.getConfigurationStore().setLinkPreviews(accountRecord.isLinkPreviewsEnabled());
210 if (accountRecord.getPhoneNumberSharingMode() != AccountRecord.PhoneNumberSharingMode.UNRECOGNIZED) {
211 account.getConfigurationStore()
212 .setPhoneNumberSharingMode(switch (accountRecord.getPhoneNumberSharingMode()) {
213 case EVERYBODY -> PhoneNumberSharingMode.EVERYBODY;
214 case NOBODY -> PhoneNumberSharingMode.NOBODY;
215 default -> PhoneNumberSharingMode.CONTACTS;
216 });
217 }
218 account.getConfigurationStore().setPhoneNumberUnlisted(accountRecord.isPhoneNumberUnlisted());
219
220 if (accountRecord.getProfileKey().isPresent()) {
221 ProfileKey profileKey;
222 try {
223 profileKey = new ProfileKey(accountRecord.getProfileKey().get());
224 } catch (InvalidInputException e) {
225 logger.warn("Received invalid profile key from storage");
226 profileKey = null;
227 }
228 if (profileKey != null) {
229 account.setProfileKey(profileKey);
230 final var avatarPath = accountRecord.getAvatarUrlPath().orElse(null);
231 context.getProfileHelper().downloadProfileAvatar(account.getSelfRecipientId(), avatarPath, profileKey);
232 }
233 }
234
235 context.getProfileHelper()
236 .setProfile(false,
237 false,
238 accountRecord.getGivenName().orElse(null),
239 accountRecord.getFamilyName().orElse(null),
240 null,
241 null,
242 null,
243 null);
244 }
245
246 private SignalStorageRecord getSignalStorageRecord(final StorageId accountId) throws IOException {
247 List<SignalStorageRecord> records;
248 try {
249 records = dependencies.getAccountManager()
250 .readStorageRecords(account.getStorageKey(), Collections.singletonList(accountId));
251 } catch (InvalidKeyException e) {
252 logger.warn("Failed to read storage records, ignoring.");
253 return null;
254 }
255 return records.size() > 0 ? records.get(0) : null;
256 }
257
258 private List<SignalStorageRecord> getSignalStorageRecords(final Collection<StorageId> storageIds) throws IOException {
259 List<SignalStorageRecord> records;
260 try {
261 records = dependencies.getAccountManager()
262 .readStorageRecords(account.getStorageKey(), new ArrayList<>(storageIds));
263 } catch (InvalidKeyException e) {
264 logger.warn("Failed to read storage records, ignoring.");
265 return List.of();
266 }
267 return records;
268 }
269 }