]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/StorageHelper.java
257cea8373bb68cfd6616aac4defc70b13dc7e7c
[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.asamk.signal.manager.storage.recipients.Profile;
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;
24
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;
32
33 public class StorageHelper {
34
35 private final static Logger logger = LoggerFactory.getLogger(StorageHelper.class);
36
37 private final SignalAccount account;
38 private final SignalDependencies dependencies;
39 private final Context context;
40
41 public StorageHelper(final Context context) {
42 this.account = context.getAccount();
43 this.dependencies = context.getDependencies();
44 this.context = context;
45 }
46
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();
52 return;
53 }
54
55 logger.debug("Reading data from remote storage");
56 Optional<SignalStorageManifest> manifest;
57 try {
58 manifest = dependencies.getAccountManager()
59 .getStorageManifestIfDifferentVersion(storageKey, account.getStorageManifestVersion());
60 } catch (InvalidKeyException e) {
61 logger.warn("Manifest couldn't be decrypted, ignoring.");
62 return;
63 }
64
65 if (manifest.isEmpty()) {
66 logger.debug("Manifest is up to date, does not exist or couldn't be decrypted, ignoring.");
67 return;
68 }
69
70 logger.trace("Remote storage manifest has {} records", manifest.get().getStorageIds().size());
71 final var storageIds = manifest.get()
72 .getStorageIds()
73 .stream()
74 .filter(id -> !id.isUnknown())
75 .collect(Collectors.toSet());
76
77 Optional<SignalStorageManifest> localManifest = account.getStorageManifest();
78 localManifest.ifPresent(m -> m.getStorageIds().forEach(storageIds::remove));
79
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);
91 }
92 }
93 account.setStorageManifestVersion(manifest.get().getVersion());
94 account.setStorageManifest(manifest.get());
95 logger.debug("Done reading data from remote storage");
96 }
97
98 private void readContactRecord(final SignalStorageRecord record) {
99 if (record == null || record.getContact().isEmpty()) {
100 return;
101 }
102
103 final var contactRecord = record.getContact().get();
104 final var address = new RecipientAddress(contactRecord.getServiceId(), contactRecord.getNumber().orElse(null));
105 final var recipientId = account.getRecipientResolver().resolveRecipient(address);
106
107 final var contact = account.getContactStore().getContact(recipientId);
108 final var blocked = contact != null && contact.isBlocked();
109 final var profileShared = contact != null && contact.isProfileSharingEnabled();
110 final var archived = contact != null && contact.isArchived();
111 final var contactGivenName = contact == null ? null : contact.getGivenName();
112 final var contactFamilyName = contact == null ? null : contact.getFamilyName();
113 if (blocked != contactRecord.isBlocked()
114 || profileShared != contactRecord.isProfileSharingEnabled()
115 || archived != contactRecord.isArchived()
116 || (
117 contactRecord.getSystemGivenName().isPresent() && !contactRecord.getSystemGivenName()
118 .get()
119 .equals(contactGivenName)
120 )
121 || (
122 contactRecord.getSystemFamilyName().isPresent() && !contactRecord.getSystemFamilyName()
123 .get()
124 .equals(contactFamilyName)
125 )) {
126 logger.debug("Storing new or updated contact {}", recipientId);
127 final var contactBuilder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
128 final var newContact = contactBuilder.withBlocked(contactRecord.isBlocked())
129 .withProfileSharingEnabled(contactRecord.isProfileSharingEnabled())
130 .withArchived(contactRecord.isArchived());
131 if (contactRecord.getSystemGivenName().isPresent() || contactRecord.getSystemFamilyName().isPresent()) {
132 newContact.withGivenName(contactRecord.getSystemGivenName().orElse(null))
133 .withFamilyName(contactRecord.getSystemFamilyName().orElse(null));
134 }
135 account.getContactStore().storeContact(recipientId, newContact.build());
136 }
137
138 final var profile = account.getProfileStore().getProfile(recipientId);
139 final var profileGivenName = profile == null ? null : profile.getGivenName();
140 final var profileFamilyName = profile == null ? null : profile.getFamilyName();
141 if ((
142 contactRecord.getProfileGivenName().isPresent() && !contactRecord.getProfileGivenName()
143 .get()
144 .equals(profileGivenName)
145 ) || (
146 contactRecord.getProfileFamilyName().isPresent() && !contactRecord.getProfileFamilyName()
147 .get()
148 .equals(profileFamilyName)
149 )) {
150 final var profileBuilder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
151 final var newProfile = profileBuilder.withGivenName(contactRecord.getProfileGivenName().orElse(null))
152 .withFamilyName(contactRecord.getProfileFamilyName().orElse(null))
153 .build();
154 account.getProfileStore().storeProfile(recipientId, newProfile);
155 }
156 if (contactRecord.getProfileKey().isPresent()) {
157 try {
158 logger.trace("Storing profile key {}", recipientId);
159 final var profileKey = new ProfileKey(contactRecord.getProfileKey().get());
160 account.getProfileStore().storeProfileKey(recipientId, profileKey);
161 } catch (InvalidInputException e) {
162 logger.warn("Received invalid contact profile key from storage");
163 }
164 }
165 if (contactRecord.getIdentityKey().isPresent()) {
166 try {
167 logger.trace("Storing identity key {}", recipientId);
168 final var identityKey = new IdentityKey(contactRecord.getIdentityKey().get());
169 account.getIdentityKeyStore().saveIdentity(address.getServiceId(), identityKey);
170
171 final var trustLevel = TrustLevel.fromIdentityState(contactRecord.getIdentityState());
172 if (trustLevel != null) {
173 account.getIdentityKeyStore()
174 .setIdentityTrustLevel(address.getServiceId(), identityKey, trustLevel);
175 }
176 } catch (InvalidKeyException e) {
177 logger.warn("Received invalid contact identity key from storage");
178 }
179 }
180 }
181
182 private void readGroupV1Record(final SignalStorageRecord record) {
183 if (record == null || record.getGroupV1().isEmpty()) {
184 return;
185 }
186
187 final var groupV1Record = record.getGroupV1().get();
188 final var groupIdV1 = GroupId.v1(groupV1Record.getGroupId());
189
190 var group = account.getGroupStore().getGroup(groupIdV1);
191 if (group == null) {
192 try {
193 context.getGroupHelper().sendGroupInfoRequest(groupIdV1, account.getSelfRecipientId());
194 } catch (Throwable e) {
195 logger.warn("Failed to send group request", e);
196 }
197 group = account.getGroupStore().getOrCreateGroupV1(groupIdV1);
198 }
199 if (group != null && group.isBlocked() != groupV1Record.isBlocked()) {
200 group.setBlocked(groupV1Record.isBlocked());
201 account.getGroupStore().updateGroup(group);
202 }
203 }
204
205 private void readGroupV2Record(final SignalStorageRecord record) {
206 if (record == null || record.getGroupV2().isEmpty()) {
207 return;
208 }
209
210 final var groupV2Record = record.getGroupV2().get();
211 if (groupV2Record.isArchived()) {
212 return;
213 }
214
215 final GroupMasterKey groupMasterKey;
216 try {
217 groupMasterKey = new GroupMasterKey(groupV2Record.getMasterKeyBytes());
218 } catch (InvalidInputException e) {
219 logger.warn("Received invalid group master key from storage");
220 return;
221 }
222
223 final var group = context.getGroupHelper().getOrMigrateGroup(groupMasterKey, 0, null);
224 if (group.isBlocked() != groupV2Record.isBlocked()) {
225 group.setBlocked(groupV2Record.isBlocked());
226 account.getGroupStore().updateGroup(group);
227 }
228 }
229
230 private void readAccountRecord(final SignalStorageRecord record) throws IOException {
231 if (record == null) {
232 logger.warn("Could not find account record, even though we had an ID, ignoring.");
233 return;
234 }
235
236 SignalAccountRecord accountRecord = record.getAccount().orElse(null);
237 if (accountRecord == null) {
238 logger.warn("The storage record didn't actually have an account, ignoring.");
239 return;
240 }
241
242 if (!accountRecord.getE164().equals(account.getNumber())) {
243 context.getAccountHelper().checkWhoAmiI();
244 }
245
246 account.getConfigurationStore().setReadReceipts(accountRecord.isReadReceiptsEnabled());
247 account.getConfigurationStore().setTypingIndicators(accountRecord.isTypingIndicatorsEnabled());
248 account.getConfigurationStore()
249 .setUnidentifiedDeliveryIndicators(accountRecord.isSealedSenderIndicatorsEnabled());
250 account.getConfigurationStore().setLinkPreviews(accountRecord.isLinkPreviewsEnabled());
251 if (accountRecord.getPhoneNumberSharingMode() != AccountRecord.PhoneNumberSharingMode.UNRECOGNIZED) {
252 account.getConfigurationStore()
253 .setPhoneNumberSharingMode(switch (accountRecord.getPhoneNumberSharingMode()) {
254 case EVERYBODY -> PhoneNumberSharingMode.EVERYBODY;
255 case NOBODY -> PhoneNumberSharingMode.NOBODY;
256 default -> PhoneNumberSharingMode.CONTACTS;
257 });
258 }
259 account.getConfigurationStore().setPhoneNumberUnlisted(accountRecord.isPhoneNumberUnlisted());
260
261 if (accountRecord.getProfileKey().isPresent()) {
262 ProfileKey profileKey;
263 try {
264 profileKey = new ProfileKey(accountRecord.getProfileKey().get());
265 } catch (InvalidInputException e) {
266 logger.warn("Received invalid profile key from storage");
267 profileKey = null;
268 }
269 if (profileKey != null) {
270 account.setProfileKey(profileKey);
271 final var avatarPath = accountRecord.getAvatarUrlPath().orElse(null);
272 context.getProfileHelper().downloadProfileAvatar(account.getSelfRecipientId(), avatarPath, profileKey);
273 }
274 }
275
276 context.getProfileHelper()
277 .setProfile(false,
278 false,
279 accountRecord.getGivenName().orElse(null),
280 accountRecord.getFamilyName().orElse(null),
281 null,
282 null,
283 null,
284 null);
285 }
286
287 private SignalStorageRecord getSignalStorageRecord(final StorageId accountId) throws IOException {
288 List<SignalStorageRecord> records;
289 try {
290 records = dependencies.getAccountManager()
291 .readStorageRecords(account.getStorageKey(), Collections.singletonList(accountId));
292 } catch (InvalidKeyException e) {
293 logger.warn("Failed to read storage records, ignoring.");
294 return null;
295 }
296 return records.size() > 0 ? records.get(0) : null;
297 }
298
299 private List<SignalStorageRecord> getSignalStorageRecords(final Collection<StorageId> storageIds) throws IOException {
300 List<SignalStorageRecord> records;
301 try {
302 records = dependencies.getAccountManager()
303 .readStorageRecords(account.getStorageKey(), new ArrayList<>(storageIds));
304 } catch (InvalidKeyException e) {
305 logger.warn("Failed to read storage records, ignoring.");
306 return List.of();
307 }
308 return records;
309 }
310 }