]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/StorageHelper.java
15684da54b03a91e6e21b36fa429d1eb48093e0d
[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().uuid(),
105 contactRecord.getNumber().orElse(null));
106 final var recipientId = account.getRecipientResolver().resolveRecipient(address);
107
108 final var contact = account.getContactStore().getContact(recipientId);
109 final var blocked = contact != null && contact.isBlocked();
110 final var profileShared = contact != null && contact.isProfileSharingEnabled();
111 final var archived = contact != null && contact.isArchived();
112 final var contactGivenName = contact == null ? null : contact.getGivenName();
113 final var contactFamilyName = contact == null ? null : contact.getFamilyName();
114 if (blocked != contactRecord.isBlocked()
115 || profileShared != contactRecord.isProfileSharingEnabled()
116 || archived != contactRecord.isArchived()
117 || (
118 contactRecord.getSystemGivenName().isPresent() && !contactRecord.getSystemGivenName()
119 .get()
120 .equals(contactGivenName)
121 )
122 || (
123 contactRecord.getSystemFamilyName().isPresent() && !contactRecord.getSystemFamilyName()
124 .get()
125 .equals(contactFamilyName)
126 )) {
127 logger.debug("Storing new or updated contact {}", recipientId);
128 final var contactBuilder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
129 final var newContact = contactBuilder.withBlocked(contactRecord.isBlocked())
130 .withProfileSharingEnabled(contactRecord.isProfileSharingEnabled())
131 .withArchived(contactRecord.isArchived());
132 if (contactRecord.getSystemGivenName().isPresent() || contactRecord.getSystemFamilyName().isPresent()) {
133 newContact.withGivenName(contactRecord.getSystemGivenName().orElse(null))
134 .withFamilyName(contactRecord.getSystemFamilyName().orElse(null));
135 }
136 account.getContactStore().storeContact(recipientId, newContact.build());
137 }
138
139 final var profile = account.getProfileStore().getProfile(recipientId);
140 final var profileGivenName = profile == null ? null : profile.getGivenName();
141 final var profileFamilyName = profile == null ? null : profile.getFamilyName();
142 if ((
143 contactRecord.getProfileGivenName().isPresent() && !contactRecord.getProfileGivenName()
144 .get()
145 .equals(profileGivenName)
146 ) || (
147 contactRecord.getProfileFamilyName().isPresent() && !contactRecord.getProfileFamilyName()
148 .get()
149 .equals(profileFamilyName)
150 )) {
151 final var profileBuilder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
152 final var newProfile = profileBuilder.withGivenName(contactRecord.getProfileGivenName().orElse(null))
153 .withFamilyName(contactRecord.getProfileFamilyName().orElse(null))
154 .build();
155 account.getProfileStore().storeProfile(recipientId, newProfile);
156 }
157 if (contactRecord.getProfileKey().isPresent()) {
158 try {
159 logger.trace("Storing profile key {}", recipientId);
160 final var profileKey = new ProfileKey(contactRecord.getProfileKey().get());
161 account.getProfileStore().storeProfileKey(recipientId, profileKey);
162 } catch (InvalidInputException e) {
163 logger.warn("Received invalid contact profile key from storage");
164 }
165 }
166 if (contactRecord.getIdentityKey().isPresent()) {
167 try {
168 logger.trace("Storing identity key {}", recipientId);
169 final var identityKey = new IdentityKey(contactRecord.getIdentityKey().get());
170 account.getIdentityKeyStore().saveIdentity(address.getServiceId(), identityKey);
171
172 final var trustLevel = TrustLevel.fromIdentityState(contactRecord.getIdentityState());
173 if (trustLevel != null) {
174 account.getIdentityKeyStore()
175 .setIdentityTrustLevel(address.getServiceId(), identityKey, trustLevel);
176 }
177 } catch (InvalidKeyException e) {
178 logger.warn("Received invalid contact identity key from storage");
179 }
180 }
181 }
182
183 private void readGroupV1Record(final SignalStorageRecord record) {
184 if (record == null || record.getGroupV1().isEmpty()) {
185 return;
186 }
187
188 final var groupV1Record = record.getGroupV1().get();
189 final var groupIdV1 = GroupId.v1(groupV1Record.getGroupId());
190
191 var group = account.getGroupStore().getGroup(groupIdV1);
192 if (group == null) {
193 try {
194 context.getGroupHelper().sendGroupInfoRequest(groupIdV1, account.getSelfRecipientId());
195 } catch (Throwable e) {
196 logger.warn("Failed to send group request", e);
197 }
198 group = account.getGroupStore().getOrCreateGroupV1(groupIdV1);
199 }
200 if (group != null && group.isBlocked() != groupV1Record.isBlocked()) {
201 group.setBlocked(groupV1Record.isBlocked());
202 account.getGroupStore().updateGroup(group);
203 }
204 }
205
206 private void readGroupV2Record(final SignalStorageRecord record) {
207 if (record == null || record.getGroupV2().isEmpty()) {
208 return;
209 }
210
211 final var groupV2Record = record.getGroupV2().get();
212 if (groupV2Record.isArchived()) {
213 return;
214 }
215
216 final GroupMasterKey groupMasterKey;
217 try {
218 groupMasterKey = new GroupMasterKey(groupV2Record.getMasterKeyBytes());
219 } catch (InvalidInputException e) {
220 logger.warn("Received invalid group master key from storage");
221 return;
222 }
223
224 final var group = context.getGroupHelper().getOrMigrateGroup(groupMasterKey, 0, null);
225 if (group.isBlocked() != groupV2Record.isBlocked()) {
226 group.setBlocked(groupV2Record.isBlocked());
227 account.getGroupStore().updateGroup(group);
228 }
229 }
230
231 private void readAccountRecord(final SignalStorageRecord record) throws IOException {
232 if (record == null) {
233 logger.warn("Could not find account record, even though we had an ID, ignoring.");
234 return;
235 }
236
237 SignalAccountRecord accountRecord = record.getAccount().orElse(null);
238 if (accountRecord == null) {
239 logger.warn("The storage record didn't actually have an account, ignoring.");
240 return;
241 }
242
243 if (!accountRecord.getE164().equals(account.getNumber())) {
244 context.getAccountHelper().checkWhoAmiI();
245 }
246
247 account.getConfigurationStore().setReadReceipts(accountRecord.isReadReceiptsEnabled());
248 account.getConfigurationStore().setTypingIndicators(accountRecord.isTypingIndicatorsEnabled());
249 account.getConfigurationStore()
250 .setUnidentifiedDeliveryIndicators(accountRecord.isSealedSenderIndicatorsEnabled());
251 account.getConfigurationStore().setLinkPreviews(accountRecord.isLinkPreviewsEnabled());
252 if (accountRecord.getPhoneNumberSharingMode() != AccountRecord.PhoneNumberSharingMode.UNRECOGNIZED) {
253 account.getConfigurationStore()
254 .setPhoneNumberSharingMode(switch (accountRecord.getPhoneNumberSharingMode()) {
255 case EVERYBODY -> PhoneNumberSharingMode.EVERYBODY;
256 case NOBODY -> PhoneNumberSharingMode.NOBODY;
257 default -> PhoneNumberSharingMode.CONTACTS;
258 });
259 }
260 account.getConfigurationStore().setPhoneNumberUnlisted(accountRecord.isPhoneNumberUnlisted());
261
262 if (accountRecord.getProfileKey().isPresent()) {
263 ProfileKey profileKey;
264 try {
265 profileKey = new ProfileKey(accountRecord.getProfileKey().get());
266 } catch (InvalidInputException e) {
267 logger.warn("Received invalid profile key from storage");
268 profileKey = null;
269 }
270 if (profileKey != null) {
271 account.setProfileKey(profileKey);
272 final var avatarPath = accountRecord.getAvatarUrlPath().orElse(null);
273 context.getProfileHelper().downloadProfileAvatar(account.getSelfRecipientId(), avatarPath, profileKey);
274 }
275 }
276
277 context.getProfileHelper()
278 .setProfile(false,
279 false,
280 accountRecord.getGivenName().orElse(null),
281 accountRecord.getFamilyName().orElse(null),
282 null,
283 null,
284 null,
285 null);
286 }
287
288 private SignalStorageRecord getSignalStorageRecord(final StorageId accountId) throws IOException {
289 List<SignalStorageRecord> records;
290 try {
291 records = dependencies.getAccountManager()
292 .readStorageRecords(account.getStorageKey(), Collections.singletonList(accountId));
293 } catch (InvalidKeyException e) {
294 logger.warn("Failed to read storage records, ignoring.");
295 return null;
296 }
297 return records.size() > 0 ? records.get(0) : null;
298 }
299
300 private List<SignalStorageRecord> getSignalStorageRecords(final Collection<StorageId> storageIds) throws IOException {
301 List<SignalStorageRecord> records;
302 try {
303 records = dependencies.getAccountManager()
304 .readStorageRecords(account.getStorageKey(), new ArrayList<>(storageIds));
305 } catch (InvalidKeyException e) {
306 logger.warn("Failed to read storage records, ignoring.");
307 return List.of();
308 }
309 return records;
310 }
311 }