]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/ProfileHelper.java
Refactor SendReceiptAction to take type argument
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / helper / ProfileHelper.java
1 package org.asamk.signal.manager.helper;
2
3 import org.asamk.signal.manager.SignalDependencies;
4 import org.asamk.signal.manager.config.ServiceConfig;
5 import org.asamk.signal.manager.groups.GroupNotFoundException;
6 import org.asamk.signal.manager.groups.NotAGroupMemberException;
7 import org.asamk.signal.manager.storage.SignalAccount;
8 import org.asamk.signal.manager.storage.groups.GroupInfoV2;
9 import org.asamk.signal.manager.storage.recipients.Profile;
10 import org.asamk.signal.manager.storage.recipients.RecipientAddress;
11 import org.asamk.signal.manager.storage.recipients.RecipientId;
12 import org.asamk.signal.manager.util.IOUtils;
13 import org.asamk.signal.manager.util.KeyUtils;
14 import org.asamk.signal.manager.util.PaymentUtils;
15 import org.asamk.signal.manager.util.ProfileUtils;
16 import org.asamk.signal.manager.util.Utils;
17 import org.signal.libsignal.protocol.IdentityKey;
18 import org.signal.libsignal.protocol.InvalidKeyException;
19 import org.signal.libsignal.zkgroup.profiles.ProfileKey;
20 import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredential;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23 import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess;
24 import org.whispersystems.signalservice.api.profiles.AvatarUploadParams;
25 import org.whispersystems.signalservice.api.profiles.ProfileAndCredential;
26 import org.whispersystems.signalservice.api.profiles.SignalServiceProfile;
27 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
28 import org.whispersystems.signalservice.api.push.exceptions.NotFoundException;
29 import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException;
30 import org.whispersystems.signalservice.api.services.ProfileService;
31
32 import java.io.File;
33 import java.io.IOException;
34 import java.io.OutputStream;
35 import java.nio.file.Files;
36 import java.util.Base64;
37 import java.util.Collection;
38 import java.util.Date;
39 import java.util.List;
40 import java.util.Locale;
41 import java.util.Objects;
42 import java.util.Optional;
43 import java.util.Set;
44
45 import io.reactivex.rxjava3.core.Flowable;
46 import io.reactivex.rxjava3.core.Maybe;
47 import io.reactivex.rxjava3.core.Single;
48
49 public final class ProfileHelper {
50
51 private final static Logger logger = LoggerFactory.getLogger(ProfileHelper.class);
52
53 private final SignalAccount account;
54 private final SignalDependencies dependencies;
55 private final Context context;
56
57 public ProfileHelper(final Context context) {
58 this.account = context.getAccount();
59 this.dependencies = context.getDependencies();
60 this.context = context;
61 }
62
63 public void rotateProfileKey() throws IOException {
64 // refresh our profile, before creating a new profile key
65 getSelfProfile();
66 var profileKey = KeyUtils.createProfileKey();
67 account.setProfileKey(profileKey);
68 context.getAccountHelper().updateAccountAttributes();
69 setProfile(true, true, null, null, null, null, null, null);
70 // TODO update profile key in storage
71
72 final var recipientIds = account.getRecipientStore().getRecipientIdsWithEnabledProfileSharing();
73 for (final var recipientId : recipientIds) {
74 context.getSendHelper().sendProfileKey(recipientId);
75 }
76
77 final var selfRecipientId = account.getSelfRecipientId();
78 final var activeGroupIds = account.getGroupStore()
79 .getGroups()
80 .stream()
81 .filter(g -> g instanceof GroupInfoV2 && g.isMember(selfRecipientId))
82 .map(g -> (GroupInfoV2) g)
83 .map(GroupInfoV2::getGroupId)
84 .toList();
85 for (final var groupId : activeGroupIds) {
86 try {
87 context.getGroupHelper().updateGroupProfileKey(groupId);
88 } catch (GroupNotFoundException | NotAGroupMemberException | IOException e) {
89 logger.warn("Failed to update group profile key: {}", e.getMessage());
90 }
91 }
92 }
93
94 public Profile getRecipientProfile(RecipientId recipientId) {
95 return getRecipientProfile(recipientId, false);
96 }
97
98 public List<Profile> getRecipientProfiles(Collection<RecipientId> recipientIds) {
99 return getRecipientProfiles(recipientIds, false);
100 }
101
102 public void refreshRecipientProfile(RecipientId recipientId) {
103 getRecipientProfile(recipientId, true);
104 }
105
106 public void refreshRecipientProfiles(Collection<RecipientId> recipientIds) {
107 getRecipientProfiles(recipientIds, true);
108 }
109
110 public List<ProfileKeyCredential> getRecipientProfileKeyCredential(List<RecipientId> recipientIds) {
111 try {
112 account.getRecipientStore().setBulkUpdating(true);
113 final var profileFetches = Flowable.fromIterable(recipientIds)
114 .filter(recipientId -> account.getProfileStore().getProfileKeyCredential(recipientId) == null)
115 .map(recipientId -> retrieveProfile(recipientId,
116 SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL).onErrorComplete());
117 Maybe.merge(profileFetches, 10).blockingSubscribe();
118 } finally {
119 account.getRecipientStore().setBulkUpdating(false);
120 }
121
122 return recipientIds.stream().map(r -> account.getProfileStore().getProfileKeyCredential(r)).toList();
123 }
124
125 public ProfileKeyCredential getRecipientProfileKeyCredential(RecipientId recipientId) {
126 var profileKeyCredential = account.getProfileStore().getProfileKeyCredential(recipientId);
127 if (profileKeyCredential != null) {
128 return profileKeyCredential;
129 }
130
131 try {
132 blockingGetProfile(retrieveProfile(recipientId, SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL));
133 } catch (IOException e) {
134 logger.warn("Failed to retrieve profile key credential, ignoring: {}", e.getMessage());
135 return null;
136 }
137
138 return account.getProfileStore().getProfileKeyCredential(recipientId);
139 }
140
141 /**
142 * @param givenName if null, the previous givenName will be kept
143 * @param familyName if null, the previous familyName will be kept
144 * @param about if null, the previous about text will be kept
145 * @param aboutEmoji if null, the previous about emoji will be kept
146 * @param avatar if avatar is null the image from the local avatar store is used (if present),
147 */
148 public void setProfile(
149 String givenName,
150 final String familyName,
151 String about,
152 String aboutEmoji,
153 Optional<File> avatar,
154 byte[] mobileCoinAddress
155 ) throws IOException {
156 setProfile(true, false, givenName, familyName, about, aboutEmoji, avatar, mobileCoinAddress);
157 }
158
159 public void setProfile(
160 boolean uploadProfile,
161 boolean forceUploadAvatar,
162 String givenName,
163 final String familyName,
164 String about,
165 String aboutEmoji,
166 Optional<File> avatar,
167 byte[] mobileCoinAddress
168 ) throws IOException {
169 var profile = getSelfProfile();
170 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
171 if (givenName != null) {
172 builder.withGivenName(givenName);
173 }
174 if (familyName != null) {
175 builder.withFamilyName(familyName);
176 }
177 if (about != null) {
178 builder.withAbout(about);
179 }
180 if (aboutEmoji != null) {
181 builder.withAboutEmoji(aboutEmoji);
182 }
183 if (mobileCoinAddress != null) {
184 builder.withMobileCoinAddress(mobileCoinAddress);
185 }
186 var newProfile = builder.build();
187
188 if (uploadProfile) {
189 final var streamDetails = avatar != null && avatar.isPresent()
190 ? Utils.createStreamDetailsFromFile(avatar.get())
191 : forceUploadAvatar && avatar == null ? context.getAvatarStore()
192 .retrieveProfileAvatar(account.getSelfRecipientAddress()) : null;
193 try (streamDetails) {
194 final var avatarUploadParams = streamDetails != null
195 ? AvatarUploadParams.forAvatar(streamDetails)
196 : avatar == null ? AvatarUploadParams.unchanged(true) : AvatarUploadParams.unchanged(false);
197 final var paymentsAddress = Optional.ofNullable(newProfile.getMobileCoinAddress())
198 .map(address -> PaymentUtils.signPaymentsAddress(address,
199 account.getAciIdentityKeyPair().getPrivateKey()));
200 logger.debug("Uploading new profile");
201 final var avatarPath = dependencies.getAccountManager()
202 .setVersionedProfile(account.getAci(),
203 account.getProfileKey(),
204 newProfile.getInternalServiceName(),
205 newProfile.getAbout() == null ? "" : newProfile.getAbout(),
206 newProfile.getAboutEmoji() == null ? "" : newProfile.getAboutEmoji(),
207 paymentsAddress,
208 avatarUploadParams,
209 List.of(/* TODO implement support for badges */));
210 if (!avatarUploadParams.keepTheSame) {
211 builder.withAvatarUrlPath(avatarPath.orElse(null));
212 }
213 newProfile = builder.build();
214 }
215 }
216
217 if (avatar != null) {
218 if (avatar.isPresent()) {
219 context.getAvatarStore()
220 .storeProfileAvatar(account.getSelfRecipientAddress(),
221 outputStream -> IOUtils.copyFileToStream(avatar.get(), outputStream));
222 } else {
223 context.getAvatarStore().deleteProfileAvatar(account.getSelfRecipientAddress());
224 }
225 }
226 account.getProfileStore().storeProfile(account.getSelfRecipientId(), newProfile);
227 }
228
229 public Profile getSelfProfile() {
230 return getRecipientProfile(account.getSelfRecipientId());
231 }
232
233 private List<Profile> getRecipientProfiles(Collection<RecipientId> recipientIds, boolean force) {
234 final var profileStore = account.getProfileStore();
235 try {
236 account.getRecipientStore().setBulkUpdating(true);
237 final var profileFetches = Flowable.fromIterable(recipientIds)
238 .filter(recipientId -> force || isProfileRefreshRequired(profileStore.getProfile(recipientId)))
239 .map(recipientId -> retrieveProfile(recipientId,
240 SignalServiceProfile.RequestType.PROFILE).onErrorComplete());
241 Maybe.merge(profileFetches, 10).blockingSubscribe();
242 } finally {
243 account.getRecipientStore().setBulkUpdating(false);
244 }
245
246 return recipientIds.stream().map(profileStore::getProfile).toList();
247 }
248
249 private Profile getRecipientProfile(RecipientId recipientId, boolean force) {
250 var profile = account.getProfileStore().getProfile(recipientId);
251
252 if (!force && !isProfileRefreshRequired(profile)) {
253 return profile;
254 }
255
256 try {
257 blockingGetProfile(retrieveProfile(recipientId, SignalServiceProfile.RequestType.PROFILE));
258 } catch (IOException e) {
259 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
260 }
261
262 return account.getProfileStore().getProfile(recipientId);
263 }
264
265 private boolean isProfileRefreshRequired(final Profile profile) {
266 if (profile == null) {
267 return true;
268 }
269 // Profiles are cached for 6h before retrieving them again, unless forced
270 final var now = System.currentTimeMillis();
271 return now - profile.getLastUpdateTimestamp() >= 6 * 60 * 60 * 1000;
272 }
273
274 private SignalServiceProfile retrieveProfileSync(String username) throws IOException {
275 final var locale = Utils.getDefaultLocale(Locale.US);
276 return dependencies.getMessageReceiver().retrieveProfileByUsername(username, Optional.empty(), locale);
277 }
278
279 private Profile decryptProfileAndDownloadAvatar(
280 final RecipientId recipientId, final ProfileKey profileKey, final SignalServiceProfile encryptedProfile
281 ) {
282 final var avatarPath = encryptedProfile.getAvatar();
283 downloadProfileAvatar(recipientId, avatarPath, profileKey);
284
285 return ProfileUtils.decryptProfile(profileKey, encryptedProfile);
286 }
287
288 public void downloadProfileAvatar(
289 final RecipientId recipientId, final String avatarPath, final ProfileKey profileKey
290 ) {
291 var profile = account.getProfileStore().getProfile(recipientId);
292 if (profile == null || !Objects.equals(avatarPath, profile.getAvatarUrlPath())) {
293 logger.trace("Downloading profile avatar for {}", recipientId);
294 downloadProfileAvatar(account.getRecipientAddressResolver().resolveRecipientAddress(recipientId),
295 avatarPath,
296 profileKey);
297 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
298 account.getProfileStore().storeProfile(recipientId, builder.withAvatarUrlPath(avatarPath).build());
299 }
300 }
301
302 private ProfileAndCredential blockingGetProfile(Single<ProfileAndCredential> profile) throws IOException {
303 try {
304 return profile.blockingGet();
305 } catch (RuntimeException e) {
306 if (e.getCause() instanceof PushNetworkException) {
307 throw (PushNetworkException) e.getCause();
308 } else if (e.getCause() instanceof NotFoundException) {
309 throw (NotFoundException) e.getCause();
310 } else {
311 throw new IOException(e);
312 }
313 }
314 }
315
316 private Single<ProfileAndCredential> retrieveProfile(
317 RecipientId recipientId, SignalServiceProfile.RequestType requestType
318 ) {
319 var unidentifiedAccess = getUnidentifiedAccess(recipientId);
320 var profileKey = Optional.ofNullable(account.getProfileStore().getProfileKey(recipientId));
321
322 logger.trace("Retrieving profile for {} {}",
323 recipientId,
324 profileKey.isPresent() ? "with profile key" : "without profile key");
325 final var address = context.getRecipientHelper().resolveSignalServiceAddress(recipientId);
326 return retrieveProfile(address, profileKey, unidentifiedAccess, requestType).doOnSuccess(p -> {
327 logger.trace("Got new profile for {}", recipientId);
328 final var encryptedProfile = p.getProfile();
329
330 if (requestType == SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL
331 || account.getProfileStore().getProfileKeyCredential(recipientId) == null) {
332 logger.trace("Storing profile credential");
333 final var profileKeyCredential = p.getProfileKeyCredential().orElse(null);
334 account.getProfileStore().storeProfileKeyCredential(recipientId, profileKeyCredential);
335 }
336
337 final var profile = account.getProfileStore().getProfile(recipientId);
338
339 Profile newProfile = null;
340 if (profileKey.isPresent()) {
341 logger.trace("Decrypting profile");
342 newProfile = decryptProfileAndDownloadAvatar(recipientId, profileKey.get(), encryptedProfile);
343 }
344
345 if (newProfile == null) {
346 newProfile = (
347 profile == null ? Profile.newBuilder() : Profile.newBuilder(profile)
348 ).withLastUpdateTimestamp(System.currentTimeMillis())
349 .withUnidentifiedAccessMode(ProfileUtils.getUnidentifiedAccessMode(encryptedProfile, null))
350 .withCapabilities(ProfileUtils.getCapabilities(encryptedProfile))
351 .build();
352 }
353
354 try {
355 logger.trace("Storing identity");
356 final var identityKey = new IdentityKey(Base64.getDecoder().decode(encryptedProfile.getIdentityKey()));
357 account.getIdentityKeyStore().saveIdentity(recipientId, identityKey, new Date());
358 } catch (InvalidKeyException ignored) {
359 logger.warn("Got invalid identity key in profile for {}",
360 context.getRecipientHelper().resolveSignalServiceAddress(recipientId).getIdentifier());
361 }
362
363 logger.trace("Storing profile");
364 account.getProfileStore().storeProfile(recipientId, newProfile);
365
366 logger.trace("Done handling retrieved profile");
367 }).doOnError(e -> {
368 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
369 final var profile = account.getProfileStore().getProfile(recipientId);
370 final var newProfile = (
371 profile == null ? Profile.newBuilder() : Profile.newBuilder(profile)
372 ).withLastUpdateTimestamp(System.currentTimeMillis())
373 .withUnidentifiedAccessMode(Profile.UnidentifiedAccessMode.UNKNOWN)
374 .withCapabilities(Set.of())
375 .build();
376
377 account.getProfileStore().storeProfile(recipientId, newProfile);
378 });
379 }
380
381 private Single<ProfileAndCredential> retrieveProfile(
382 SignalServiceAddress address,
383 Optional<ProfileKey> profileKey,
384 Optional<UnidentifiedAccess> unidentifiedAccess,
385 SignalServiceProfile.RequestType requestType
386 ) {
387 final var profileService = dependencies.getProfileService();
388 final var locale = Utils.getDefaultLocale(Locale.US);
389
390 return profileService.getProfile(address, profileKey, unidentifiedAccess, requestType, locale).map(pair -> {
391 var processor = new ProfileService.ProfileResponseProcessor(pair);
392 if (processor.hasResult()) {
393 return processor.getResult();
394 } else if (processor.notFound()) {
395 throw new NotFoundException("Profile not found");
396 } else {
397 throw pair.getExecutionError()
398 .or(pair::getApplicationError)
399 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
400 }
401 });
402 }
403
404 private void downloadProfileAvatar(
405 RecipientAddress address, String avatarPath, ProfileKey profileKey
406 ) {
407 if (avatarPath == null) {
408 try {
409 context.getAvatarStore().deleteProfileAvatar(address);
410 } catch (IOException e) {
411 logger.warn("Failed to delete local profile avatar, ignoring: {}", e.getMessage());
412 }
413 return;
414 }
415
416 try {
417 context.getAvatarStore()
418 .storeProfileAvatar(address,
419 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
420 } catch (Throwable e) {
421 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
422 }
423 }
424
425 private void retrieveProfileAvatar(
426 String avatarPath, ProfileKey profileKey, OutputStream outputStream
427 ) throws IOException {
428 var tmpFile = IOUtils.createTempFile();
429 try (var input = dependencies.getMessageReceiver()
430 .retrieveProfileAvatar(avatarPath,
431 tmpFile,
432 profileKey,
433 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
434 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
435 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
436 } finally {
437 try {
438 Files.delete(tmpFile.toPath());
439 } catch (IOException e) {
440 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
441 tmpFile,
442 e.getMessage());
443 }
444 }
445 }
446
447 private Optional<UnidentifiedAccess> getUnidentifiedAccess(RecipientId recipientId) {
448 var unidentifiedAccess = context.getUnidentifiedAccessHelper().getAccessFor(recipientId, true);
449
450 if (unidentifiedAccess.isPresent()) {
451 return unidentifiedAccess.get().getTargetUnidentifiedAccess();
452 }
453
454 return Optional.empty();
455 }
456 }